Merge "MotionEvent: Round coordinates to a precision of 0.001" into udc-dev
diff --git a/include/ftl/details/optional.h b/include/ftl/details/optional.h
index bff7c1e..e45c1f5 100644
--- a/include/ftl/details/optional.h
+++ b/include/ftl/details/optional.h
@@ -54,5 +54,15 @@
template <typename F, typename T>
using and_then_result_t = typename and_then_result<F, T>::type;
+template <typename F, typename T>
+struct or_else_result {
+ using type = remove_cvref_t<std::invoke_result_t<F>>;
+ static_assert(std::is_same_v<type, std::optional<T>> || std::is_same_v<type, Optional<T>>,
+ "or_else function must return an optional T");
+};
+
+template <typename F, typename T>
+using or_else_result_t = typename or_else_result<F, T>::type;
+
} // namespace details
} // namespace android::ftl
diff --git a/include/ftl/optional.h b/include/ftl/optional.h
index a818128..94d8e3d 100644
--- a/include/ftl/optional.h
+++ b/include/ftl/optional.h
@@ -96,13 +96,25 @@
return R();
}
+ // Returns this Optional<T> if not nullopt, or else the Optional<T> returned by the function F.
+ template <typename F>
+ constexpr auto or_else(F&& f) const& -> details::or_else_result_t<F, T> {
+ if (has_value()) return *this;
+ return std::forward<F>(f)();
+ }
+
+ template <typename F>
+ constexpr auto or_else(F&& f) && -> details::or_else_result_t<F, T> {
+ if (has_value()) return std::move(*this);
+ return std::forward<F>(f)();
+ }
+
// Delete new for this class. Its base doesn't have a virtual destructor, and
// if it got deleted via base class pointer, it would cause undefined
// behavior. There's not a good reason to allocate this object on the heap
// anyway.
static void* operator new(size_t) = delete;
static void* operator new[](size_t) = delete;
-
};
template <typename T, typename U>
diff --git a/include/input/PropertyMap.h b/include/input/PropertyMap.h
index 18ce16d..28e4816 100644
--- a/include/input/PropertyMap.h
+++ b/include/input/PropertyMap.h
@@ -18,10 +18,7 @@
#include <android-base/result.h>
#include <utils/Tokenizer.h>
-
-#include <string>
#include <unordered_map>
-#include <unordered_set>
namespace android {
@@ -60,9 +57,6 @@
*/
void addProperty(const std::string& key, const std::string& value);
- /* Returns a set of all property keys starting with the given prefix. */
- std::unordered_set<std::string> getKeysWithPrefix(const std::string& prefix) const;
-
/* Gets the value of a property and parses it.
* Returns true and sets outValue if the key was found and its value was parsed successfully.
* Otherwise returns false and does not modify outValue. (Also logs a warning.)
@@ -71,7 +65,6 @@
bool tryGetProperty(const std::string& key, bool& outValue) const;
bool tryGetProperty(const std::string& key, int32_t& outValue) const;
bool tryGetProperty(const std::string& key, float& outValue) const;
- bool tryGetProperty(const std::string& key, double& outValue) const;
/* Adds all values from the specified property map. */
void addAll(const PropertyMap* map);
diff --git a/libs/ftl/optional_test.cpp b/libs/ftl/optional_test.cpp
index 6b3b6c4..91bf7bc 100644
--- a/libs/ftl/optional_test.cpp
+++ b/libs/ftl/optional_test.cpp
@@ -164,6 +164,46 @@
}));
}
+TEST(Optional, OrElse) {
+ // Non-empty.
+ {
+ const Optional opt = false;
+ EXPECT_EQ(false, opt.or_else([] { return Optional(true); }));
+ EXPECT_EQ('x', Optional('x').or_else([] { return std::make_optional('y'); }));
+ }
+
+ // Empty.
+ {
+ const Optional<int> opt;
+ EXPECT_EQ(123, opt.or_else([]() -> Optional<int> { return 123; }));
+ EXPECT_EQ("abc"s, Optional<std::string>().or_else([] { return Optional("abc"s); }));
+ }
+ {
+ bool empty = false;
+ EXPECT_EQ(Optional<float>(), Optional<float>().or_else([&empty]() -> Optional<float> {
+ empty = true;
+ return std::nullopt;
+ }));
+ EXPECT_TRUE(empty);
+ }
+
+ // Chaining.
+ using StringVector = StaticVector<std::string, 3>;
+ EXPECT_EQ(999, Optional(StaticVector{"1"s, "0"s, "0"s})
+ .and_then([](StringVector&& v) -> Optional<StringVector> {
+ if (v.push_back("0"s)) return v;
+ return {};
+ })
+ .or_else([] {
+ return Optional(StaticVector{"9"s, "9"s, "9"s});
+ })
+ .transform([](const StringVector& v) {
+ return std::accumulate(v.begin(), v.end(), std::string());
+ })
+ .and_then(parse_int)
+ .or_else([] { return Optional(-1); }));
+}
+
// Comparison.
namespace {
diff --git a/libs/input/Android.bp b/libs/input/Android.bp
index 869458c..f38dd98 100644
--- a/libs/input/Android.bp
+++ b/libs/input/Android.bp
@@ -167,7 +167,6 @@
cc_defaults {
name: "libinput_fuzz_defaults",
- cpp_std: "c++20",
host_supported: true,
shared_libs: [
"libutils",
diff --git a/libs/input/PropertyMap.cpp b/libs/input/PropertyMap.cpp
index 9a4f10b..ed9ac9f 100644
--- a/libs/input/PropertyMap.cpp
+++ b/libs/input/PropertyMap.cpp
@@ -16,8 +16,6 @@
#define LOG_TAG "PropertyMap"
-#include <cstdlib>
-
#include <input/PropertyMap.h>
#include <log/log.h>
@@ -46,16 +44,6 @@
mProperties.emplace(key, value);
}
-std::unordered_set<std::string> PropertyMap::getKeysWithPrefix(const std::string& prefix) const {
- std::unordered_set<std::string> keys;
- for (const auto& [key, _] : mProperties) {
- if (key.starts_with(prefix)) {
- keys.insert(key);
- }
- }
- return keys;
-}
-
bool PropertyMap::hasProperty(const std::string& key) const {
return mProperties.find(key) != mProperties.end();
}
@@ -114,23 +102,6 @@
return true;
}
-bool PropertyMap::tryGetProperty(const std::string& key, double& outValue) const {
- std::string stringValue;
- if (!tryGetProperty(key, stringValue) || stringValue.length() == 0) {
- return false;
- }
-
- char* end;
- double value = strtod(stringValue.c_str(), &end);
- if (*end != '\0') {
- ALOGW("Property key '%s' has invalid value '%s'. Expected a double.", key.c_str(),
- stringValue.c_str());
- return false;
- }
- outValue = value;
- return true;
-}
-
void PropertyMap::addAll(const PropertyMap* map) {
for (const auto& [key, value] : map->mProperties) {
mProperties.emplace(key, value);
diff --git a/libs/jpegrecoverymap/Android.bp b/libs/jpegrecoverymap/Android.bp
index 0c03ede..b470f35 100644
--- a/libs/jpegrecoverymap/Android.bp
+++ b/libs/jpegrecoverymap/Android.bp
@@ -29,6 +29,7 @@
local_include_dirs: ["include"],
srcs: [
+ "icc.cpp",
"jpegr.cpp",
"recoverymapmath.cpp",
"jpegrutils.cpp",
@@ -43,8 +44,6 @@
"liblog",
"libutils",
],
-
- static_libs: ["libskia"],
}
cc_library {
diff --git a/libs/jpegrecoverymap/icc.cpp b/libs/jpegrecoverymap/icc.cpp
new file mode 100644
index 0000000..5412cb1
--- /dev/null
+++ b/libs/jpegrecoverymap/icc.cpp
@@ -0,0 +1,584 @@
+/*
+ * Copyright 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.
+ */
+
+#include <jpegrecoverymap/icc.h>
+#include <jpegrecoverymap/recoverymapmath.h>
+#include <vector>
+#include <utils/Log.h>
+
+#ifndef FLT_MAX
+#define FLT_MAX 0x1.fffffep127f
+#endif
+
+namespace android::jpegrecoverymap {
+static void Matrix3x3_apply(const Matrix3x3* m, float* x) {
+ float y0 = x[0] * m->vals[0][0] + x[1] * m->vals[0][1] + x[2] * m->vals[0][2];
+ float y1 = x[0] * m->vals[1][0] + x[1] * m->vals[1][1] + x[2] * m->vals[1][2];
+ float y2 = x[0] * m->vals[2][0] + x[1] * m->vals[2][1] + x[2] * m->vals[2][2];
+ x[0] = y0;
+ x[1] = y1;
+ x[2] = y2;
+}
+
+bool Matrix3x3_invert(const Matrix3x3* src, Matrix3x3* dst) {
+ double a00 = src->vals[0][0],
+ a01 = src->vals[1][0],
+ a02 = src->vals[2][0],
+ a10 = src->vals[0][1],
+ a11 = src->vals[1][1],
+ a12 = src->vals[2][1],
+ a20 = src->vals[0][2],
+ a21 = src->vals[1][2],
+ a22 = src->vals[2][2];
+
+ double b0 = a00*a11 - a01*a10,
+ b1 = a00*a12 - a02*a10,
+ b2 = a01*a12 - a02*a11,
+ b3 = a20,
+ b4 = a21,
+ b5 = a22;
+
+ double determinant = b0*b5
+ - b1*b4
+ + b2*b3;
+
+ if (determinant == 0) {
+ return false;
+ }
+
+ double invdet = 1.0 / determinant;
+ if (invdet > +FLT_MAX || invdet < -FLT_MAX || !isfinitef_((float)invdet)) {
+ return false;
+ }
+
+ b0 *= invdet;
+ b1 *= invdet;
+ b2 *= invdet;
+ b3 *= invdet;
+ b4 *= invdet;
+ b5 *= invdet;
+
+ dst->vals[0][0] = (float)( a11*b5 - a12*b4 );
+ dst->vals[1][0] = (float)( a02*b4 - a01*b5 );
+ dst->vals[2][0] = (float)( + b2 );
+ dst->vals[0][1] = (float)( a12*b3 - a10*b5 );
+ dst->vals[1][1] = (float)( a00*b5 - a02*b3 );
+ dst->vals[2][1] = (float)( - b1 );
+ dst->vals[0][2] = (float)( a10*b4 - a11*b3 );
+ dst->vals[1][2] = (float)( a01*b3 - a00*b4 );
+ dst->vals[2][2] = (float)( + b0 );
+
+ for (int r = 0; r < 3; ++r)
+ for (int c = 0; c < 3; ++c) {
+ if (!isfinitef_(dst->vals[r][c])) {
+ return false;
+ }
+ }
+ return true;
+}
+
+static Matrix3x3 Matrix3x3_concat(const Matrix3x3* A, const Matrix3x3* B) {
+ Matrix3x3 m = { { { 0,0,0 },{ 0,0,0 },{ 0,0,0 } } };
+ for (int r = 0; r < 3; r++)
+ for (int c = 0; c < 3; c++) {
+ m.vals[r][c] = A->vals[r][0] * B->vals[0][c]
+ + A->vals[r][1] * B->vals[1][c]
+ + A->vals[r][2] * B->vals[2][c];
+ }
+ return m;
+}
+
+static void float_XYZD50_to_grid16_lab(const float* xyz_float, uint8_t* grid16_lab) {
+ float v[3] = {
+ xyz_float[0] / kD50_x,
+ xyz_float[1] / kD50_y,
+ xyz_float[2] / kD50_z,
+ };
+ for (size_t i = 0; i < 3; ++i) {
+ v[i] = v[i] > 0.008856f ? cbrtf(v[i]) : v[i] * 7.787f + (16 / 116.0f);
+ }
+ const float L = v[1] * 116.0f - 16.0f;
+ const float a = (v[0] - v[1]) * 500.0f;
+ const float b = (v[1] - v[2]) * 200.0f;
+ const float Lab_unorm[3] = {
+ L * (1 / 100.f),
+ (a + 128.0f) * (1 / 255.0f),
+ (b + 128.0f) * (1 / 255.0f),
+ };
+ // This will encode L=1 as 0xFFFF. This matches how skcms will interpret the
+ // table, but the spec appears to indicate that the value should be 0xFF00.
+ // https://crbug.com/skia/13807
+ for (size_t i = 0; i < 3; ++i) {
+ reinterpret_cast<uint16_t*>(grid16_lab)[i] =
+ Endian_SwapBE16(float_round_to_unorm16(Lab_unorm[i]));
+ }
+}
+
+std::string IccHelper::get_desc_string(const jpegr_transfer_function tf,
+ const jpegr_color_gamut gamut) {
+ std::string result;
+ switch (gamut) {
+ case JPEGR_COLORGAMUT_BT709:
+ result += "sRGB";
+ break;
+ case JPEGR_COLORGAMUT_P3:
+ result += "Display P3";
+ break;
+ case JPEGR_COLORGAMUT_BT2100:
+ result += "Rec2020";
+ break;
+ default:
+ result += "Unknown";
+ break;
+ }
+ result += " Gamut with ";
+ switch (tf) {
+ case JPEGR_TF_SRGB:
+ result += "sRGB";
+ break;
+ case JPEGR_TF_LINEAR:
+ result += "Linear";
+ break;
+ case JPEGR_TF_PQ:
+ result += "PQ";
+ break;
+ case JPEGR_TF_HLG:
+ result += "HLG";
+ break;
+ default:
+ result += "Unknown";
+ break;
+ }
+ result += " Transfer";
+ return result;
+}
+
+sp<DataStruct> IccHelper::write_text_tag(const char* text) {
+ uint32_t text_length = strlen(text);
+ uint32_t header[] = {
+ Endian_SwapBE32(kTAG_TextType), // Type signature
+ 0, // Reserved
+ Endian_SwapBE32(1), // Number of records
+ Endian_SwapBE32(12), // Record size (must be 12)
+ Endian_SwapBE32(SetFourByteTag('e', 'n', 'U', 'S')), // English USA
+ Endian_SwapBE32(2 * text_length), // Length of string in bytes
+ Endian_SwapBE32(28), // Offset of string
+ };
+
+ uint32_t total_length = text_length * 2 + sizeof(header);
+ total_length = (((total_length + 2) >> 2) << 2); // 4 aligned
+ sp<DataStruct> dataStruct = new DataStruct(total_length);
+
+ if (!dataStruct->write(header, sizeof(header))) {
+ ALOGE("write_text_tag(): error in writing data");
+ return dataStruct;
+ }
+
+ for (size_t i = 0; i < text_length; i++) {
+ // Convert ASCII to big-endian UTF-16.
+ dataStruct->write8(0);
+ dataStruct->write8(text[i]);
+ }
+
+ return dataStruct;
+}
+
+sp<DataStruct> IccHelper::write_xyz_tag(float x, float y, float z) {
+ uint32_t data[] = {
+ Endian_SwapBE32(kXYZ_PCSSpace),
+ 0,
+ static_cast<uint32_t>(Endian_SwapBE32(float_round_to_fixed(x))),
+ static_cast<uint32_t>(Endian_SwapBE32(float_round_to_fixed(y))),
+ static_cast<uint32_t>(Endian_SwapBE32(float_round_to_fixed(z))),
+ };
+ sp<DataStruct> dataStruct = new DataStruct(sizeof(data));
+ dataStruct->write(&data, sizeof(data));
+ return dataStruct;
+}
+
+sp<DataStruct> IccHelper::write_trc_tag(const int table_entries, const void* table_16) {
+ int total_length = 4 + 4 + 4 + table_entries * 2;
+ total_length = (((total_length + 2) >> 2) << 2); // 4 aligned
+ sp<DataStruct> dataStruct = new DataStruct(total_length);
+ dataStruct->write32(Endian_SwapBE32(kTAG_CurveType)); // Type
+ dataStruct->write32(0); // Reserved
+ dataStruct->write32(Endian_SwapBE32(table_entries)); // Value count
+ for (size_t i = 0; i < table_entries; ++i) {
+ uint16_t value = reinterpret_cast<const uint16_t*>(table_16)[i];
+ dataStruct->write16(value);
+ }
+ return dataStruct;
+}
+
+sp<DataStruct> IccHelper::write_trc_tag_for_linear() {
+ int total_length = 16;
+ sp<DataStruct> dataStruct = new DataStruct(total_length);
+ dataStruct->write32(Endian_SwapBE32(kTAG_ParaCurveType)); // Type
+ dataStruct->write32(0); // Reserved
+ dataStruct->write32(Endian_SwapBE16(kExponential_ParaCurveType));
+ dataStruct->write32(Endian_SwapBE32(float_round_to_fixed(1.0)));
+
+ return dataStruct;
+}
+
+float IccHelper::compute_tone_map_gain(const jpegr_transfer_function tf, float L) {
+ if (L <= 0.f) {
+ return 1.f;
+ }
+ if (tf == JPEGR_TF_PQ) {
+ // The PQ transfer function will map to the range [0, 1]. Linearly scale
+ // it up to the range [0, 10,000/203]. We will then tone map that back
+ // down to [0, 1].
+ constexpr float kInputMaxLuminance = 10000 / 203.f;
+ constexpr float kOutputMaxLuminance = 1.0;
+ L *= kInputMaxLuminance;
+
+ // Compute the tone map gain which will tone map from 10,000/203 to 1.0.
+ constexpr float kToneMapA = kOutputMaxLuminance / (kInputMaxLuminance * kInputMaxLuminance);
+ constexpr float kToneMapB = 1.f / kOutputMaxLuminance;
+ return kInputMaxLuminance * (1.f + kToneMapA * L) / (1.f + kToneMapB * L);
+ }
+ if (tf == JPEGR_TF_HLG) {
+ // Let Lw be the brightness of the display in nits.
+ constexpr float Lw = 203.f;
+ const float gamma = 1.2f + 0.42f * std::log(Lw / 1000.f) / std::log(10.f);
+ return std::pow(L, gamma - 1.f);
+ }
+ return 1.f;
+}
+
+sp<DataStruct> IccHelper::write_cicp_tag(uint32_t color_primaries,
+ uint32_t transfer_characteristics) {
+ int total_length = 12; // 4 + 4 + 1 + 1 + 1 + 1
+ sp<DataStruct> dataStruct = new DataStruct(total_length);
+ dataStruct->write32(Endian_SwapBE32(kTAG_cicp)); // Type signature
+ dataStruct->write32(0); // Reserved
+ dataStruct->write8(color_primaries); // Color primaries
+ dataStruct->write8(transfer_characteristics); // Transfer characteristics
+ dataStruct->write8(0); // RGB matrix
+ dataStruct->write8(1); // Full range
+ return dataStruct;
+}
+
+void IccHelper::compute_lut_entry(const Matrix3x3& src_to_XYZD50, float rgb[3]) {
+ // Compute the matrices to convert from source to Rec2020, and from Rec2020 to XYZD50.
+ Matrix3x3 src_to_rec2020;
+ const Matrix3x3 rec2020_to_XYZD50 = kRec2020;
+ {
+ Matrix3x3 XYZD50_to_rec2020;
+ Matrix3x3_invert(&rec2020_to_XYZD50, &XYZD50_to_rec2020);
+ src_to_rec2020 = Matrix3x3_concat(&XYZD50_to_rec2020, &src_to_XYZD50);
+ }
+
+ // Convert the source signal to linear.
+ for (size_t i = 0; i < kNumChannels; ++i) {
+ rgb[i] = pqOetf(rgb[i]);
+ }
+
+ // Convert source gamut to Rec2020.
+ Matrix3x3_apply(&src_to_rec2020, rgb);
+
+ // Compute the luminance of the signal.
+ float L = bt2100Luminance({{{rgb[0], rgb[1], rgb[2]}}});
+
+ // Compute the tone map gain based on the luminance.
+ float tone_map_gain = compute_tone_map_gain(JPEGR_TF_PQ, L);
+
+ // Apply the tone map gain.
+ for (size_t i = 0; i < kNumChannels; ++i) {
+ rgb[i] *= tone_map_gain;
+ }
+
+ // Convert from Rec2020-linear to XYZD50.
+ Matrix3x3_apply(&rec2020_to_XYZD50, rgb);
+}
+
+sp<DataStruct> IccHelper::write_clut(const uint8_t* grid_points, const uint8_t* grid_16) {
+ uint32_t value_count = kNumChannels;
+ for (uint32_t i = 0; i < kNumChannels; ++i) {
+ value_count *= grid_points[i];
+ }
+
+ int total_length = 20 + 2 * value_count;
+ total_length = (((total_length + 2) >> 2) << 2); // 4 aligned
+ sp<DataStruct> dataStruct = new DataStruct(total_length);
+
+ for (size_t i = 0; i < 16; ++i) {
+ dataStruct->write8(i < kNumChannels ? grid_points[i] : 0); // Grid size
+ }
+ dataStruct->write8(2); // Grid byte width (always 16-bit)
+ dataStruct->write8(0); // Reserved
+ dataStruct->write8(0); // Reserved
+ dataStruct->write8(0); // Reserved
+
+ for (uint32_t i = 0; i < value_count; ++i) {
+ uint16_t value = reinterpret_cast<const uint16_t*>(grid_16)[i];
+ dataStruct->write16(value);
+ }
+
+ return dataStruct;
+}
+
+sp<DataStruct> IccHelper::write_mAB_or_mBA_tag(uint32_t type,
+ bool has_a_curves,
+ const uint8_t* grid_points,
+ const uint8_t* grid_16) {
+ const size_t b_curves_offset = 32;
+ sp<DataStruct> b_curves_data[kNumChannels];
+ sp<DataStruct> a_curves_data[kNumChannels];
+ size_t clut_offset = 0;
+ sp<DataStruct> clut;
+ size_t a_curves_offset = 0;
+
+ // The "B" curve is required.
+ for (size_t i = 0; i < kNumChannels; ++i) {
+ b_curves_data[i] = write_trc_tag_for_linear();
+ }
+
+ // The "A" curve and CLUT are optional.
+ if (has_a_curves) {
+ clut_offset = b_curves_offset;
+ for (size_t i = 0; i < kNumChannels; ++i) {
+ clut_offset += b_curves_data[i]->getLength();
+ }
+ clut = write_clut(grid_points, grid_16);
+
+ a_curves_offset = clut_offset + clut->getLength();
+ for (size_t i = 0; i < kNumChannels; ++i) {
+ a_curves_data[i] = write_trc_tag_for_linear();
+ }
+ }
+
+ int total_length = b_curves_offset;
+ for (size_t i = 0; i < kNumChannels; ++i) {
+ total_length += b_curves_data[i]->getLength();
+ }
+ if (has_a_curves) {
+ total_length += clut->getLength();
+ for (size_t i = 0; i < kNumChannels; ++i) {
+ total_length += a_curves_data[i]->getLength();
+ }
+ }
+ sp<DataStruct> dataStruct = new DataStruct(total_length);
+ dataStruct->write32(Endian_SwapBE32(type)); // Type signature
+ dataStruct->write32(0); // Reserved
+ dataStruct->write8(kNumChannels); // Input channels
+ dataStruct->write8(kNumChannels); // Output channels
+ dataStruct->write16(0); // Reserved
+ dataStruct->write32(Endian_SwapBE32(b_curves_offset)); // B curve offset
+ dataStruct->write32(Endian_SwapBE32(0)); // Matrix offset (ignored)
+ dataStruct->write32(Endian_SwapBE32(0)); // M curve offset (ignored)
+ dataStruct->write32(Endian_SwapBE32(clut_offset)); // CLUT offset
+ dataStruct->write32(Endian_SwapBE32(a_curves_offset)); // A curve offset
+ for (size_t i = 0; i < kNumChannels; ++i) {
+ if (dataStruct->write(b_curves_data[i]->getData(), b_curves_data[i]->getLength())) {
+ return dataStruct;
+ }
+ }
+ if (has_a_curves) {
+ dataStruct->write(clut->getData(), clut->getLength());
+ for (size_t i = 0; i < kNumChannels; ++i) {
+ dataStruct->write(a_curves_data[i]->getData(), a_curves_data[i]->getLength());
+ }
+ }
+ return dataStruct;
+}
+
+sp<DataStruct> IccHelper::writeIccProfile(jpegr_transfer_function tf, jpegr_color_gamut gamut) {
+ ICCHeader header;
+
+ std::vector<std::pair<uint32_t, sp<DataStruct>>> tags;
+
+ // Compute profile description tag
+ std::string desc = get_desc_string(tf, gamut);
+
+ tags.emplace_back(kTAG_desc, write_text_tag(desc.c_str()));
+
+ Matrix3x3 toXYZD50;
+ switch (gamut) {
+ case JPEGR_COLORGAMUT_BT709:
+ toXYZD50 = kSRGB;
+ break;
+ case JPEGR_COLORGAMUT_P3:
+ toXYZD50 = kDisplayP3;
+ break;
+ case JPEGR_COLORGAMUT_BT2100:
+ toXYZD50 = kRec2020;
+ break;
+ default:
+ // Should not fall here.
+ return new DataStruct(0);
+ }
+
+ // Compute primaries.
+ {
+ tags.emplace_back(kTAG_rXYZ,
+ write_xyz_tag(toXYZD50.vals[0][0], toXYZD50.vals[1][0], toXYZD50.vals[2][0]));
+ tags.emplace_back(kTAG_gXYZ,
+ write_xyz_tag(toXYZD50.vals[0][1], toXYZD50.vals[1][1], toXYZD50.vals[2][1]));
+ tags.emplace_back(kTAG_bXYZ,
+ write_xyz_tag(toXYZD50.vals[0][2], toXYZD50.vals[1][2], toXYZD50.vals[2][2]));
+ }
+
+ // Compute white point tag (must be D50)
+ tags.emplace_back(kTAG_wtpt, write_xyz_tag(kD50_x, kD50_y, kD50_z));
+
+ // Compute transfer curves.
+ if (tf != JPEGR_TF_PQ) {
+ if (tf == JPEGR_TF_HLG) {
+ std::vector<uint8_t> trc_table;
+ trc_table.resize(kTrcTableSize * 2);
+ for (uint32_t i = 0; i < kTrcTableSize; ++i) {
+ float x = i / (kTrcTableSize - 1.f);
+ float y = hlgOetf(x);
+ y *= compute_tone_map_gain(tf, y);
+ float_to_table16(y, &trc_table[2 * i]);
+ }
+
+ tags.emplace_back(kTAG_rTRC,
+ write_trc_tag(kTrcTableSize, reinterpret_cast<uint8_t*>(trc_table.data())));
+ tags.emplace_back(kTAG_gTRC,
+ write_trc_tag(kTrcTableSize, reinterpret_cast<uint8_t*>(trc_table.data())));
+ tags.emplace_back(kTAG_bTRC,
+ write_trc_tag(kTrcTableSize, reinterpret_cast<uint8_t*>(trc_table.data())));
+ } else {
+ tags.emplace_back(kTAG_rTRC, write_trc_tag_for_linear());
+ tags.emplace_back(kTAG_gTRC, write_trc_tag_for_linear());
+ tags.emplace_back(kTAG_bTRC, write_trc_tag_for_linear());
+ }
+ }
+
+ // Compute CICP.
+ if (tf == JPEGR_TF_HLG || tf == JPEGR_TF_PQ) {
+ // The CICP tag is present in ICC 4.4, so update the header's version.
+ header.version = Endian_SwapBE32(0x04400000);
+
+ uint32_t color_primaries = 0;
+ if (gamut == JPEGR_COLORGAMUT_BT709) {
+ color_primaries = kCICPPrimariesSRGB;
+ } else if (gamut == JPEGR_COLORGAMUT_P3) {
+ color_primaries = kCICPPrimariesP3;
+ }
+
+ uint32_t transfer_characteristics = 0;
+ if (tf == JPEGR_TF_SRGB) {
+ transfer_characteristics = kCICPTrfnSRGB;
+ } else if (tf == JPEGR_TF_LINEAR) {
+ transfer_characteristics = kCICPTrfnLinear;
+ } else if (tf == JPEGR_TF_PQ) {
+ transfer_characteristics = kCICPTrfnPQ;
+ } else if (tf == JPEGR_TF_HLG) {
+ transfer_characteristics = kCICPTrfnHLG;
+ }
+ tags.emplace_back(kTAG_cicp, write_cicp_tag(color_primaries, transfer_characteristics));
+ }
+
+ // Compute A2B0.
+ if (tf == JPEGR_TF_PQ) {
+ std::vector<uint8_t> a2b_grid;
+ a2b_grid.resize(kGridSize * kGridSize * kGridSize * kNumChannels * 2);
+ size_t a2b_grid_index = 0;
+ for (uint32_t r_index = 0; r_index < kGridSize; ++r_index) {
+ for (uint32_t g_index = 0; g_index < kGridSize; ++g_index) {
+ for (uint32_t b_index = 0; b_index < kGridSize; ++b_index) {
+ float rgb[3] = {
+ r_index / (kGridSize - 1.f),
+ g_index / (kGridSize - 1.f),
+ b_index / (kGridSize - 1.f),
+ };
+ compute_lut_entry(toXYZD50, rgb);
+ float_XYZD50_to_grid16_lab(rgb, &a2b_grid[a2b_grid_index]);
+ a2b_grid_index += 6;
+ }
+ }
+ }
+ const uint8_t* grid_16 = reinterpret_cast<const uint8_t*>(a2b_grid.data());
+
+ uint8_t grid_points[kNumChannels];
+ for (size_t i = 0; i < kNumChannels; ++i) {
+ grid_points[i] = kGridSize;
+ }
+
+ auto a2b_data = write_mAB_or_mBA_tag(kTAG_mABType,
+ /* has_a_curves */ true,
+ grid_points,
+ grid_16);
+ tags.emplace_back(kTAG_A2B0, std::move(a2b_data));
+ }
+
+ // Compute B2A0.
+ if (tf == JPEGR_TF_PQ) {
+ auto b2a_data = write_mAB_or_mBA_tag(kTAG_mBAType,
+ /* has_a_curves */ false,
+ /* grid_points */ nullptr,
+ /* grid_16 */ nullptr);
+ tags.emplace_back(kTAG_B2A0, std::move(b2a_data));
+ }
+
+ // Compute copyright tag
+ tags.emplace_back(kTAG_cprt, write_text_tag("Google Inc. 2022"));
+
+ // Compute the size of the profile.
+ size_t tag_data_size = 0;
+ for (const auto& tag : tags) {
+ tag_data_size += tag.second->getLength();
+ }
+ size_t tag_table_size = kICCTagTableEntrySize * tags.size();
+ size_t profile_size = kICCHeaderSize + tag_table_size + tag_data_size;
+
+ // Write the header.
+ header.data_color_space = Endian_SwapBE32(Signature_RGB);
+ header.pcs = Endian_SwapBE32(tf == JPEGR_TF_PQ ? Signature_Lab : Signature_XYZ);
+ header.size = Endian_SwapBE32(profile_size);
+ header.tag_count = Endian_SwapBE32(tags.size());
+
+ sp<DataStruct> dataStruct = new DataStruct(profile_size);
+ if (!dataStruct->write(&header, sizeof(header))) {
+ ALOGE("writeIccProfile(): error in header");
+ return dataStruct;
+ }
+
+ // Write the tag table. Track the offset and size of the previous tag to
+ // compute each tag's offset. An empty SkData indicates that the previous
+ // tag is to be reused.
+ uint32_t last_tag_offset = sizeof(header) + tag_table_size;
+ uint32_t last_tag_size = 0;
+ for (const auto& tag : tags) {
+ last_tag_offset = last_tag_offset + last_tag_size;
+ last_tag_size = tag.second->getLength();
+ uint32_t tag_table_entry[3] = {
+ Endian_SwapBE32(tag.first),
+ Endian_SwapBE32(last_tag_offset),
+ Endian_SwapBE32(last_tag_size),
+ };
+ if (!dataStruct->write(tag_table_entry, sizeof(tag_table_entry))) {
+ ALOGE("writeIccProfile(): error in writing tag table");
+ return dataStruct;
+ }
+ }
+
+ // Write the tags.
+ for (const auto& tag : tags) {
+ if (!dataStruct->write(tag.second->getData(), tag.second->getLength())) {
+ ALOGE("writeIccProfile(): error in writing tags");
+ return dataStruct;
+ }
+ }
+
+ return dataStruct;
+}
+
+} // namespace android::jpegrecoverymap
\ No newline at end of file
diff --git a/libs/jpegrecoverymap/include/jpegrecoverymap/icc.h b/libs/jpegrecoverymap/include/jpegrecoverymap/icc.h
new file mode 100644
index 0000000..a81aa62
--- /dev/null
+++ b/libs/jpegrecoverymap/include/jpegrecoverymap/icc.h
@@ -0,0 +1,234 @@
+/*
+ * Copyright 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_JPEGRECOVERYMAP_ICC_H
+#define ANDROID_JPEGRECOVERYMAP_ICC_H
+
+#include <jpegrecoverymap/jpegr.h>
+#include <jpegrecoverymap/jpegrutils.h>
+#include <utils/RefBase.h>
+#include <cmath>
+#include <string>
+
+#ifdef USE_BIG_ENDIAN
+#undef USE_BIG_ENDIAN
+#define USE_BIG_ENDIAN true
+#endif
+
+namespace android::jpegrecoverymap {
+
+typedef int32_t Fixed;
+#define Fixed1 (1 << 16)
+#define MaxS32FitsInFloat 2147483520
+#define MinS32FitsInFloat (-MaxS32FitsInFloat)
+#define FixedToFloat(x) ((x) * 1.52587890625e-5f)
+
+typedef struct Matrix3x3 {
+ float vals[3][3];
+} Matrix3x3;
+
+// The D50 illuminant.
+constexpr float kD50_x = 0.9642f;
+constexpr float kD50_y = 1.0000f;
+constexpr float kD50_z = 0.8249f;
+
+enum {
+ // data_color_space
+ Signature_CMYK = 0x434D594B,
+ Signature_Gray = 0x47524159,
+ Signature_RGB = 0x52474220,
+
+ // pcs
+ Signature_Lab = 0x4C616220,
+ Signature_XYZ = 0x58595A20,
+};
+
+
+typedef uint32_t FourByteTag;
+static inline constexpr FourByteTag SetFourByteTag(char a, char b, char c, char d) {
+ return (((uint32_t)a << 24) | ((uint32_t)b << 16) | ((uint32_t)c << 8) | (uint32_t)d);
+}
+
+// This is equal to the header size according to the ICC specification (128)
+// plus the size of the tag count (4). We include the tag count since we
+// always require it to be present anyway.
+static constexpr size_t kICCHeaderSize = 132;
+
+// Contains a signature (4), offset (4), and size (4).
+static constexpr size_t kICCTagTableEntrySize = 12;
+
+static constexpr uint32_t kDisplay_Profile = SetFourByteTag('m', 'n', 't', 'r');
+static constexpr uint32_t kRGB_ColorSpace = SetFourByteTag('R', 'G', 'B', ' ');
+static constexpr uint32_t kXYZ_PCSSpace = SetFourByteTag('X', 'Y', 'Z', ' ');
+static constexpr uint32_t kACSP_Signature = SetFourByteTag('a', 'c', 's', 'p');
+
+static constexpr uint32_t kTAG_desc = SetFourByteTag('d', 'e', 's', 'c');
+static constexpr uint32_t kTAG_TextType = SetFourByteTag('m', 'l', 'u', 'c');
+static constexpr uint32_t kTAG_rXYZ = SetFourByteTag('r', 'X', 'Y', 'Z');
+static constexpr uint32_t kTAG_gXYZ = SetFourByteTag('g', 'X', 'Y', 'Z');
+static constexpr uint32_t kTAG_bXYZ = SetFourByteTag('b', 'X', 'Y', 'Z');
+static constexpr uint32_t kTAG_wtpt = SetFourByteTag('w', 't', 'p', 't');
+static constexpr uint32_t kTAG_rTRC = SetFourByteTag('r', 'T', 'R', 'C');
+static constexpr uint32_t kTAG_gTRC = SetFourByteTag('g', 'T', 'R', 'C');
+static constexpr uint32_t kTAG_bTRC = SetFourByteTag('b', 'T', 'R', 'C');
+static constexpr uint32_t kTAG_cicp = SetFourByteTag('c', 'i', 'c', 'p');
+static constexpr uint32_t kTAG_cprt = SetFourByteTag('c', 'p', 'r', 't');
+static constexpr uint32_t kTAG_A2B0 = SetFourByteTag('A', '2', 'B', '0');
+static constexpr uint32_t kTAG_B2A0 = SetFourByteTag('B', '2', 'A', '0');
+
+static constexpr uint32_t kTAG_CurveType = SetFourByteTag('c', 'u', 'r', 'v');
+static constexpr uint32_t kTAG_mABType = SetFourByteTag('m', 'A', 'B', ' ');
+static constexpr uint32_t kTAG_mBAType = SetFourByteTag('m', 'B', 'A', ' ');
+static constexpr uint32_t kTAG_ParaCurveType = SetFourByteTag('p', 'a', 'r', 'a');
+
+
+static constexpr Matrix3x3 kSRGB = {{
+ // ICC fixed-point (16.16) representation, taken from skcms. Please keep them exactly in sync.
+ // 0.436065674f, 0.385147095f, 0.143066406f,
+ // 0.222488403f, 0.716873169f, 0.060607910f,
+ // 0.013916016f, 0.097076416f, 0.714096069f,
+ { FixedToFloat(0x6FA2), FixedToFloat(0x6299), FixedToFloat(0x24A0) },
+ { FixedToFloat(0x38F5), FixedToFloat(0xB785), FixedToFloat(0x0F84) },
+ { FixedToFloat(0x0390), FixedToFloat(0x18DA), FixedToFloat(0xB6CF) },
+}};
+
+static constexpr Matrix3x3 kDisplayP3 = {{
+ { 0.515102f, 0.291965f, 0.157153f },
+ { 0.241182f, 0.692236f, 0.0665819f },
+ { -0.00104941f, 0.0418818f, 0.784378f },
+}};
+
+static constexpr Matrix3x3 kRec2020 = {{
+ { 0.673459f, 0.165661f, 0.125100f },
+ { 0.279033f, 0.675338f, 0.0456288f },
+ { -0.00193139f, 0.0299794f, 0.797162f },
+}};
+
+static constexpr uint32_t kCICPPrimariesSRGB = 1;
+static constexpr uint32_t kCICPPrimariesP3 = 12;
+static constexpr uint32_t kCICPPrimariesRec2020 = 9;
+
+static constexpr uint32_t kCICPTrfnSRGB = 1;
+static constexpr uint32_t kCICPTrfnLinear = 8;
+static constexpr uint32_t kCICPTrfnPQ = 16;
+static constexpr uint32_t kCICPTrfnHLG = 18;
+
+enum ParaCurveType {
+ kExponential_ParaCurveType = 0,
+ kGAB_ParaCurveType = 1,
+ kGABC_ParaCurveType = 2,
+ kGABDE_ParaCurveType = 3,
+ kGABCDEF_ParaCurveType = 4,
+};
+
+/**
+ * Return the closest int for the given float. Returns MaxS32FitsInFloat for NaN.
+ */
+static inline int float_saturate2int(float x) {
+ x = x < MaxS32FitsInFloat ? x : MaxS32FitsInFloat;
+ x = x > MinS32FitsInFloat ? x : MinS32FitsInFloat;
+ return (int)x;
+}
+
+static Fixed float_round_to_fixed(float x) {
+ return float_saturate2int((float)floor((double)x * Fixed1 + 0.5));
+}
+
+static uint16_t float_round_to_unorm16(float x) {
+ x = x * 65535.f + 0.5;
+ if (x > 65535) return 65535;
+ if (x < 0) return 0;
+ return static_cast<uint16_t>(x);
+}
+
+static void float_to_table16(const float f, uint8_t* table_16) {
+ *reinterpret_cast<uint16_t*>(table_16) = Endian_SwapBE16(float_round_to_unorm16(f));
+}
+
+static bool isfinitef_(float x) { return 0 == x*0; }
+
+struct ICCHeader {
+ // Size of the profile (computed)
+ uint32_t size;
+ // Preferred CMM type (ignored)
+ uint32_t cmm_type = 0;
+ // Version 4.3 or 4.4 if CICP is included.
+ uint32_t version = Endian_SwapBE32(0x04300000);
+ // Display device profile
+ uint32_t profile_class = Endian_SwapBE32(kDisplay_Profile);
+ // RGB input color space;
+ uint32_t data_color_space = Endian_SwapBE32(kRGB_ColorSpace);
+ // Profile connection space.
+ uint32_t pcs = Endian_SwapBE32(kXYZ_PCSSpace);
+ // Date and time (ignored)
+ uint8_t creation_date_time[12] = {0};
+ // Profile signature
+ uint32_t signature = Endian_SwapBE32(kACSP_Signature);
+ // Platform target (ignored)
+ uint32_t platform = 0;
+ // Flags: not embedded, can be used independently
+ uint32_t flags = 0x00000000;
+ // Device manufacturer (ignored)
+ uint32_t device_manufacturer = 0;
+ // Device model (ignored)
+ uint32_t device_model = 0;
+ // Device attributes (ignored)
+ uint8_t device_attributes[8] = {0};
+ // Relative colorimetric rendering intent
+ uint32_t rendering_intent = Endian_SwapBE32(1);
+ // D50 standard illuminant (X, Y, Z)
+ uint32_t illuminant_X = Endian_SwapBE32(float_round_to_fixed(kD50_x));
+ uint32_t illuminant_Y = Endian_SwapBE32(float_round_to_fixed(kD50_y));
+ uint32_t illuminant_Z = Endian_SwapBE32(float_round_to_fixed(kD50_z));
+ // Profile creator (ignored)
+ uint32_t creator = 0;
+ // Profile id checksum (ignored)
+ uint8_t profile_id[16] = {0};
+ // Reserved (ignored)
+ uint8_t reserved[28] = {0};
+ // Technically not part of header, but required
+ uint32_t tag_count = 0;
+};
+
+class IccHelper {
+private:
+ static constexpr uint32_t kTrcTableSize = 65;
+ static constexpr uint32_t kGridSize = 17;
+ static constexpr size_t kNumChannels = 3;
+
+ static sp<DataStruct> write_text_tag(const char* text);
+ static std::string get_desc_string(const jpegr_transfer_function tf,
+ const jpegr_color_gamut gamut);
+ static sp<DataStruct> write_xyz_tag(float x, float y, float z);
+ static sp<DataStruct> write_trc_tag(const int table_entries, const void* table_16);
+ static sp<DataStruct> write_trc_tag_for_linear();
+ static float compute_tone_map_gain(const jpegr_transfer_function tf, float L);
+ static sp<DataStruct> write_cicp_tag(uint32_t color_primaries,
+ uint32_t transfer_characteristics);
+ static sp<DataStruct> write_mAB_or_mBA_tag(uint32_t type,
+ bool has_a_curves,
+ const uint8_t* grid_points,
+ const uint8_t* grid_16);
+ static void compute_lut_entry(const Matrix3x3& src_to_XYZD50, float rgb[3]);
+ static sp<DataStruct> write_clut(const uint8_t* grid_points, const uint8_t* grid_16);
+
+public:
+ static sp<DataStruct> writeIccProfile(const jpegr_transfer_function tf,
+ const jpegr_color_gamut gamut);
+};
+} // namespace android::jpegrecoverymap
+
+#endif //ANDROID_JPEGRECOVERYMAP_ICC_H
\ No newline at end of file
diff --git a/libs/jpegrecoverymap/include/jpegrecoverymap/jpegrutils.h b/libs/jpegrecoverymap/include/jpegrecoverymap/jpegrutils.h
index 4145853..a381743 100644
--- a/libs/jpegrecoverymap/include/jpegrecoverymap/jpegrutils.h
+++ b/libs/jpegrecoverymap/include/jpegrecoverymap/jpegrutils.h
@@ -27,6 +27,24 @@
namespace android::jpegrecoverymap {
+static constexpr uint32_t EndianSwap32(uint32_t value) {
+ return ((value & 0xFF) << 24) |
+ ((value & 0xFF00) << 8) |
+ ((value & 0xFF0000) >> 8) |
+ (value >> 24);
+}
+static inline uint16_t EndianSwap16(uint16_t value) {
+ return static_cast<uint16_t>((value >> 8) | ((value & 0xFF) << 8));
+}
+
+#if USE_BIG_ENDIAN
+ #define Endian_SwapBE32(n) EndianSwap32(n)
+ #define Endian_SwapBE16(n) EndianSwap16(n)
+#else
+ #define Endian_SwapBE32(n) (n)
+ #define Endian_SwapBE16(n) (n)
+#endif
+
struct jpegr_metadata;
/*
* Mutable data structure. Holds information for metadata.
diff --git a/libs/jpegrecoverymap/include/jpegrecoverymap/multipictureformat.h b/libs/jpegrecoverymap/include/jpegrecoverymap/multipictureformat.h
index 7dca916..cf3387d 100644
--- a/libs/jpegrecoverymap/include/jpegrecoverymap/multipictureformat.h
+++ b/libs/jpegrecoverymap/include/jpegrecoverymap/multipictureformat.h
@@ -19,25 +19,13 @@
#include <jpegrecoverymap/jpegrutils.h>
-namespace android::jpegrecoverymap {
-static constexpr uint32_t EndianSwap32(uint32_t value) {
- return ((value & 0xFF) << 24) |
- ((value & 0xFF00) << 8) |
- ((value & 0xFF0000) >> 8) |
- (value >> 24);
-}
-static inline uint16_t EndianSwap16(uint16_t value) {
- return static_cast<uint16_t>((value >> 8) | ((value & 0xFF) << 8));
-}
+#ifdef USE_BIG_ENDIAN
+#undef USE_BIG_ENDIAN
#define USE_BIG_ENDIAN true
-#if USE_BIG_ENDIAN
- #define Endian_SwapBE32(n) EndianSwap32(n)
- #define Endian_SwapBE16(n) EndianSwap16(n)
-#else
- #define Endian_SwapBE32(n) (n)
- #define Endian_SwapBE16(n) (n)
#endif
+namespace android::jpegrecoverymap {
+
constexpr size_t kNumPictures = 2;
constexpr size_t kMpEndianSize = 4;
constexpr uint16_t kTagSerializedCount = 3;
diff --git a/libs/jpegrecoverymap/jpegr.cpp b/libs/jpegrecoverymap/jpegr.cpp
index 79b1ae3..b115750 100644
--- a/libs/jpegrecoverymap/jpegr.cpp
+++ b/libs/jpegrecoverymap/jpegr.cpp
@@ -20,6 +20,7 @@
#include <jpegrecoverymap/recoverymapmath.h>
#include <jpegrecoverymap/jpegrutils.h>
#include <jpegrecoverymap/multipictureformat.h>
+#include <jpegrecoverymap/icc.h>
#include <image_io/jpeg/jpeg_marker.h>
#include <image_io/jpeg/jpeg_info.h>
@@ -27,10 +28,6 @@
#include <image_io/jpeg/jpeg_info_builder.h>
#include <image_io/base/data_segment_data_source.h>
#include <utils/Log.h>
-#include "SkColorSpace.h"
-#include "SkData.h"
-#include "SkICC.h"
-#include "SkRefCnt.h"
#include <map>
#include <memory>
@@ -89,21 +86,6 @@
return cpuCoreCount;
}
-static const map<jpegrecoverymap::jpegr_color_gamut, skcms_Matrix3x3> jrGamut_to_skGamut {
- {JPEGR_COLORGAMUT_BT709, SkNamedGamut::kSRGB},
- {JPEGR_COLORGAMUT_P3, SkNamedGamut::kDisplayP3},
- {JPEGR_COLORGAMUT_BT2100, SkNamedGamut::kRec2020},
-};
-
-static const map<
- jpegrecoverymap::jpegr_transfer_function,
- skcms_TransferFunction> jrTransFunc_to_skTransFunc {
- {JPEGR_TF_SRGB, SkNamedTransferFn::kSRGB},
- {JPEGR_TF_LINEAR, SkNamedTransferFn::kLinear},
- {JPEGR_TF_HLG, SkNamedTransferFn::kHLG},
- {JPEGR_TF_PQ, SkNamedTransferFn::kPQ},
-};
-
/* Encode API-0 */
status_t JpegR::encodeJPEGR(jr_uncompressed_ptr uncompressed_p010_image,
jpegr_transfer_function hdr_tf,
@@ -146,15 +128,14 @@
compressed_map.data = compressed_map_data.get();
JPEGR_CHECK(compressRecoveryMap(&map, &compressed_map));
- sk_sp<SkData> icc = SkWriteICCProfile(
- jrTransFunc_to_skTransFunc.at(JPEGR_TF_SRGB),
- jrGamut_to_skGamut.at(uncompressed_yuv_420_image.colorGamut));
+ sp<DataStruct> icc = IccHelper::writeIccProfile(JPEGR_TF_SRGB,
+ uncompressed_yuv_420_image.colorGamut);
JpegEncoderHelper jpeg_encoder;
if (!jpeg_encoder.compressImage(uncompressed_yuv_420_image.data,
uncompressed_yuv_420_image.width,
uncompressed_yuv_420_image.height, quality,
- icc.get()->data(), icc.get()->size())) {
+ icc->getData(), icc->getLength())) {
return ERROR_JPEGR_ENCODE_ERROR;
}
jpegr_compressed_struct jpeg;
@@ -210,15 +191,14 @@
compressed_map.data = compressed_map_data.get();
JPEGR_CHECK(compressRecoveryMap(&map, &compressed_map));
- sk_sp<SkData> icc = SkWriteICCProfile(
- jrTransFunc_to_skTransFunc.at(JPEGR_TF_SRGB),
- jrGamut_to_skGamut.at(uncompressed_yuv_420_image->colorGamut));
+ sp<DataStruct> icc = IccHelper::writeIccProfile(JPEGR_TF_SRGB,
+ uncompressed_yuv_420_image->colorGamut);
JpegEncoderHelper jpeg_encoder;
if (!jpeg_encoder.compressImage(uncompressed_yuv_420_image->data,
uncompressed_yuv_420_image->width,
uncompressed_yuv_420_image->height, quality,
- icc.get()->data(), icc.get()->size())) {
+ icc->getData(), icc->getLength())) {
return ERROR_JPEGR_ENCODE_ERROR;
}
jpegr_compressed_struct jpeg;
@@ -355,8 +335,6 @@
if (compressed_jpegr_image == nullptr || dest == nullptr) {
return ERROR_JPEGR_INVALID_NULL_PTR;
}
- // TODO: fill EXIF data
- (void) exif;
if (output_format == JPEGR_OUTPUT_SDR) {
JpegDecoderHelper jpeg_decoder;
@@ -384,6 +362,17 @@
return ERROR_JPEGR_DECODE_ERROR;
}
+ if (exif != nullptr) {
+ if (exif->data == nullptr) {
+ return ERROR_JPEGR_INVALID_NULL_PTR;
+ }
+ if (exif->length < jpeg_decoder.getEXIFSize()) {
+ return ERROR_JPEGR_BUFFER_TOO_SMALL;
+ }
+ memcpy(exif->data, jpeg_decoder.getEXIFPtr(), jpeg_decoder.getEXIFSize());
+ exif->length = jpeg_decoder.getEXIFSize();
+ }
+
JpegDecoderHelper recovery_map_decoder;
if (!recovery_map_decoder.decompressImage(compressed_map.data, compressed_map.length)) {
return ERROR_JPEGR_DECODE_ERROR;
diff --git a/libs/jpegrecoverymap/tests/Android.bp b/libs/jpegrecoverymap/tests/Android.bp
index 61b3db9..d5da7fb 100644
--- a/libs/jpegrecoverymap/tests/Android.bp
+++ b/libs/jpegrecoverymap/tests/Android.bp
@@ -39,7 +39,6 @@
"libjpegdecoder",
"libjpegencoder",
"libjpegrecoverymap",
- "libskia",
"libutils",
],
}
diff --git a/services/inputflinger/dispatcher/InputDispatcher.cpp b/services/inputflinger/dispatcher/InputDispatcher.cpp
index 78cdd0d..cd427f0 100644
--- a/services/inputflinger/dispatcher/InputDispatcher.cpp
+++ b/services/inputflinger/dispatcher/InputDispatcher.cpp
@@ -110,6 +110,8 @@
constexpr int LOGTAG_INPUT_FOCUS = 62001;
constexpr int LOGTAG_INPUT_CANCEL = 62003;
+const ui::Transform kIdentityTransform;
+
inline nsecs_t now() {
return systemTime(SYSTEM_TIME_MONOTONIC);
}
@@ -475,8 +477,8 @@
}
// Returns true if the given window can accept pointer events at the given display location.
-bool windowAcceptsTouchAt(const WindowInfo& windowInfo, int32_t displayId, int32_t x, int32_t y,
- bool isStylus) {
+bool windowAcceptsTouchAt(const WindowInfo& windowInfo, int32_t displayId, float x, float y,
+ bool isStylus, const ui::Transform& displayTransform) {
const auto inputConfig = windowInfo.inputConfig;
if (windowInfo.displayId != displayId ||
inputConfig.test(WindowInfo::InputConfig::NOT_VISIBLE)) {
@@ -486,7 +488,17 @@
if (inputConfig.test(WindowInfo::InputConfig::NOT_TOUCHABLE) && !windowCanInterceptTouch) {
return false;
}
- if (!windowInfo.touchableRegionContainsPoint(x, y)) {
+
+ // Window Manager works in the logical display coordinate space. When it specifies bounds for a
+ // window as (l, t, r, b), the range of x in [l, r) and y in [t, b) are considered to be inside
+ // the window. Points on the right and bottom edges should not be inside the window, so we need
+ // to be careful about performing a hit test when the display is rotated, since the "right" and
+ // "bottom" of the window will be different in the display (un-rotated) space compared to in the
+ // logical display in which WM determined the bounds. Perform the hit test in the logical
+ // display space to ensure these edges are considered correctly in all orientations.
+ const auto touchableRegion = displayTransform.transform(windowInfo.touchableRegion);
+ const auto p = displayTransform.transform(x, y);
+ if (!touchableRegion.contains(std::floor(p.x), std::floor(p.y))) {
return false;
}
return true;
@@ -540,19 +552,16 @@
return {};
}
-Point resolveTouchedPosition(const MotionEntry& entry) {
+std::pair<float, float> resolveTouchedPosition(const MotionEntry& entry) {
const bool isFromMouse = isFromSource(entry.source, AINPUT_SOURCE_MOUSE);
// Always dispatch mouse events to cursor position.
if (isFromMouse) {
- return Point(static_cast<int32_t>(entry.xCursorPosition),
- static_cast<int32_t>(entry.yCursorPosition));
+ return {entry.xCursorPosition, entry.yCursorPosition};
}
const int32_t pointerIndex = getMotionEventActionPointerIndex(entry.action);
- return Point(static_cast<int32_t>(
- entry.pointerCoords[pointerIndex].getAxisValue(AMOTION_EVENT_AXIS_X)),
- static_cast<int32_t>(
- entry.pointerCoords[pointerIndex].getAxisValue(AMOTION_EVENT_AXIS_Y)));
+ return {entry.pointerCoords[pointerIndex].getAxisValue(AMOTION_EVENT_AXIS_X),
+ entry.pointerCoords[pointerIndex].getAxisValue(AMOTION_EVENT_AXIS_Y)};
}
std::optional<nsecs_t> getDownTime(const EventEntry& eventEntry) {
@@ -1159,7 +1168,7 @@
}
std::pair<sp<WindowInfoHandle>, std::vector<InputTarget>>
-InputDispatcher::findTouchedWindowAtLocked(int32_t displayId, int32_t x, int32_t y, bool isStylus,
+InputDispatcher::findTouchedWindowAtLocked(int32_t displayId, float x, float y, bool isStylus,
bool ignoreDragWindow) const {
// Traverse windows from front to back to find touched window.
std::vector<InputTarget> outsideTargets;
@@ -1170,7 +1179,8 @@
}
const WindowInfo& info = *windowHandle->getInfo();
- if (!info.isSpy() && windowAcceptsTouchAt(info, displayId, x, y, isStylus)) {
+ if (!info.isSpy() &&
+ windowAcceptsTouchAt(info, displayId, x, y, isStylus, getTransformLocked(displayId))) {
return {windowHandle, outsideTargets};
}
@@ -1184,14 +1194,14 @@
}
std::vector<sp<WindowInfoHandle>> InputDispatcher::findTouchedSpyWindowsAtLocked(
- int32_t displayId, int32_t x, int32_t y, bool isStylus) const {
+ int32_t displayId, float x, float y, bool isStylus) const {
// Traverse windows from front to back and gather the touched spy windows.
std::vector<sp<WindowInfoHandle>> spyWindows;
const auto& windowHandles = getWindowHandlesLocked(displayId);
for (const sp<WindowInfoHandle>& windowHandle : windowHandles) {
const WindowInfo& info = *windowHandle->getInfo();
- if (!windowAcceptsTouchAt(info, displayId, x, y, isStylus)) {
+ if (!windowAcceptsTouchAt(info, displayId, x, y, isStylus, getTransformLocked(displayId))) {
continue;
}
if (!info.isSpy()) {
@@ -2231,8 +2241,7 @@
}
// Handle the case where we did not find a window.
if (newTouchedWindowHandle == nullptr) {
- ALOGD("No new touched window at (%" PRId32 ", %" PRId32 ") in display %" PRId32, x, y,
- displayId);
+ ALOGD("No new touched window at (%.1f, %.1f) in display %" PRId32, x, y, displayId);
// Try to assign the pointer to the first foreground window we find, if there is one.
newTouchedWindowHandle = tempTouchState.getFirstForegroundWindowHandle();
}
@@ -2270,7 +2279,8 @@
}
if (newTouchedWindows.empty()) {
- ALOGI("Dropping event because there is no touchable window at (%d, %d) on display %d.",
+ ALOGI("Dropping event because there is no touchable window at (%.1f, %.1f) on display "
+ "%d.",
x, y, displayId);
outInjectionResult = InputEventInjectionResult::FAILED;
return {};
@@ -4764,6 +4774,12 @@
return getWindowHandleLocked(focusedToken, displayId);
}
+ui::Transform InputDispatcher::getTransformLocked(int32_t displayId) const {
+ auto displayInfoIt = mDisplayInfos.find(displayId);
+ return displayInfoIt != mDisplayInfos.end() ? displayInfoIt->second.transform
+ : kIdentityTransform;
+}
+
bool InputDispatcher::canWindowReceiveMotionLocked(const sp<WindowInfoHandle>& window,
const MotionEntry& motionEntry) const {
const WindowInfo& info = *window->getInfo();
@@ -4801,7 +4817,7 @@
TouchOcclusionInfo occlusionInfo = computeTouchOcclusionInfoLocked(window, x, y);
if (!isTouchTrustedLocked(occlusionInfo)) {
if (DEBUG_TOUCH_OCCLUSION) {
- ALOGD("Stack of obscuring windows during untrusted touch (%d, %d):", x, y);
+ ALOGD("Stack of obscuring windows during untrusted touch (%.1f, %.1f):", x, y);
for (const auto& log : occlusionInfo.debugInfo) {
ALOGD("%s", log.c_str());
}
diff --git a/services/inputflinger/dispatcher/InputDispatcher.h b/services/inputflinger/dispatcher/InputDispatcher.h
index b94858b..2246d47 100644
--- a/services/inputflinger/dispatcher/InputDispatcher.h
+++ b/services/inputflinger/dispatcher/InputDispatcher.h
@@ -239,11 +239,11 @@
std::shared_ptr<EventEntry> mNextUnblockedEvent GUARDED_BY(mLock);
std::pair<sp<android::gui::WindowInfoHandle>, std::vector<InputTarget>>
- findTouchedWindowAtLocked(int32_t displayId, int32_t x, int32_t y, bool isStylus = false,
+ findTouchedWindowAtLocked(int32_t displayId, float x, float y, bool isStylus = false,
bool ignoreDragWindow = false) const REQUIRES(mLock);
std::vector<sp<android::gui::WindowInfoHandle>> findTouchedSpyWindowsAtLocked(
- int32_t displayId, int32_t x, int32_t y, bool isStylus) const REQUIRES(mLock);
+ int32_t displayId, float x, float y, bool isStylus) const REQUIRES(mLock);
sp<android::gui::WindowInfoHandle> findTouchedForegroundWindowLocked(int32_t displayId) const
REQUIRES(mLock);
@@ -374,6 +374,7 @@
int32_t displayId) const REQUIRES(mLock);
sp<android::gui::WindowInfoHandle> getWindowHandleLocked(
const sp<IBinder>& windowHandleToken) const REQUIRES(mLock);
+ ui::Transform getTransformLocked(int32_t displayId) const REQUIRES(mLock);
// Same function as above, but faster. Since displayId is provided, this avoids the need
// to loop through all displays.
diff --git a/services/inputflinger/reader/mapper/SensorInputMapper.cpp b/services/inputflinger/reader/mapper/SensorInputMapper.cpp
index f797bc9..3d60bfd 100644
--- a/services/inputflinger/reader/mapper/SensorInputMapper.cpp
+++ b/services/inputflinger/reader/mapper/SensorInputMapper.cpp
@@ -218,7 +218,7 @@
transform(prefix.begin(), prefix.end(), prefix.begin(), ::tolower);
int32_t reportingMode = 0;
- if (!tryGetProperty(prefix + ".reportingMode", reportingMode)) {
+ if (tryGetProperty(prefix + ".reportingMode", reportingMode)) {
sensorInfo.flags |= (reportingMode & REPORTING_MODE_MASK) << REPORTING_MODE_SHIFT;
}
diff --git a/services/inputflinger/reader/mapper/TouchInputMapper.cpp b/services/inputflinger/reader/mapper/TouchInputMapper.cpp
index b53fc73..96c163d 100644
--- a/services/inputflinger/reader/mapper/TouchInputMapper.cpp
+++ b/services/inputflinger/reader/mapper/TouchInputMapper.cpp
@@ -805,40 +805,39 @@
};
}
- // Compute oriented precision, scales and ranges.
- // Note that the maximum value reported is an inclusive maximum value so it is one
- // unit less than the total width or height of the display.
- // TODO(b/20508709): Calculate the oriented ranges using the input device's raw frame.
- switch (mInputDeviceOrientation) {
- case ui::ROTATION_90:
- case ui::ROTATION_270:
- mOrientedRanges.x.min = 0;
- mOrientedRanges.x.max = mDisplayBounds.height - 1;
- mOrientedRanges.x.flat = 0;
- mOrientedRanges.x.fuzz = 0;
- mOrientedRanges.x.resolution = mRawPointerAxes.y.resolution * mRawToDisplay.getScaleY();
+ // Oriented X/Y range (in the rotated display's orientation)
+ const FloatRect rawFrame = Rect{mRawPointerAxes.x.minValue, mRawPointerAxes.y.minValue,
+ mRawPointerAxes.x.maxValue, mRawPointerAxes.y.maxValue}
+ .toFloatRect();
+ const auto orientedRangeRect = mRawToRotatedDisplay.transform(rawFrame);
+ mOrientedRanges.x.min = orientedRangeRect.left;
+ mOrientedRanges.y.min = orientedRangeRect.top;
+ mOrientedRanges.x.max = orientedRangeRect.right;
+ mOrientedRanges.y.max = orientedRangeRect.bottom;
- mOrientedRanges.y.min = 0;
- mOrientedRanges.y.max = mDisplayBounds.width - 1;
- mOrientedRanges.y.flat = 0;
- mOrientedRanges.y.fuzz = 0;
- mOrientedRanges.y.resolution = mRawPointerAxes.x.resolution * mRawToDisplay.getScaleX();
- break;
+ // Oriented flat (in the rotated display's orientation)
+ const auto orientedFlat =
+ transformWithoutTranslation(mRawToRotatedDisplay,
+ {static_cast<float>(mRawPointerAxes.x.flat),
+ static_cast<float>(mRawPointerAxes.y.flat)});
+ mOrientedRanges.x.flat = std::abs(orientedFlat.x);
+ mOrientedRanges.y.flat = std::abs(orientedFlat.y);
- default:
- mOrientedRanges.x.min = 0;
- mOrientedRanges.x.max = mDisplayBounds.width - 1;
- mOrientedRanges.x.flat = 0;
- mOrientedRanges.x.fuzz = 0;
- mOrientedRanges.x.resolution = mRawPointerAxes.x.resolution * mRawToDisplay.getScaleX();
+ // Oriented fuzz (in the rotated display's orientation)
+ const auto orientedFuzz =
+ transformWithoutTranslation(mRawToRotatedDisplay,
+ {static_cast<float>(mRawPointerAxes.x.fuzz),
+ static_cast<float>(mRawPointerAxes.y.fuzz)});
+ mOrientedRanges.x.fuzz = std::abs(orientedFuzz.x);
+ mOrientedRanges.y.fuzz = std::abs(orientedFuzz.y);
- mOrientedRanges.y.min = 0;
- mOrientedRanges.y.max = mDisplayBounds.height - 1;
- mOrientedRanges.y.flat = 0;
- mOrientedRanges.y.fuzz = 0;
- mOrientedRanges.y.resolution = mRawPointerAxes.y.resolution * mRawToDisplay.getScaleY();
- break;
- }
+ // Oriented resolution (in the rotated display's orientation)
+ const auto orientedRes =
+ transformWithoutTranslation(mRawToRotatedDisplay,
+ {static_cast<float>(mRawPointerAxes.x.resolution),
+ static_cast<float>(mRawPointerAxes.y.resolution)});
+ mOrientedRanges.x.resolution = std::abs(orientedRes.x);
+ mOrientedRanges.y.resolution = std::abs(orientedRes.y);
}
void TouchInputMapper::computeInputTransforms() {
diff --git a/services/inputflinger/reader/mapper/TouchpadInputMapper.cpp b/services/inputflinger/reader/mapper/TouchpadInputMapper.cpp
index 3309767..d3af402 100644
--- a/services/inputflinger/reader/mapper/TouchpadInputMapper.cpp
+++ b/services/inputflinger/reader/mapper/TouchpadInputMapper.cpp
@@ -20,7 +20,6 @@
#include <optional>
#include <android/input.h>
-#include <ftl/enum.h>
#include <input/PrintTools.h>
#include <linux/input-event-codes.h>
#include <log/log_main.h>
@@ -217,11 +216,6 @@
std::list<NotifyArgs> TouchpadInputMapper::configure(nsecs_t when,
const InputReaderConfiguration* config,
uint32_t changes) {
- if (!changes) {
- // First time configuration
- mPropertyProvider.loadPropertiesFromIdcFile(getDeviceContext().getConfiguration());
- }
-
if (!changes || (changes & InputReaderConfiguration::CHANGE_DISPLAY_INFO)) {
std::optional<int32_t> displayId = mPointerController->getDisplayId();
ui::Rotation orientation = ui::ROTATION_0;
diff --git a/services/inputflinger/reader/mapper/gestures/PropertyProvider.cpp b/services/inputflinger/reader/mapper/gestures/PropertyProvider.cpp
index 3d88338..089f45a 100644
--- a/services/inputflinger/reader/mapper/gestures/PropertyProvider.cpp
+++ b/services/inputflinger/reader/mapper/gestures/PropertyProvider.cpp
@@ -84,29 +84,6 @@
return dump;
}
-void PropertyProvider::loadPropertiesFromIdcFile(const PropertyMap& idcProperties) {
- // For compatibility with the configuration file syntax, gesture property names in IDC files are
- // prefixed with "gestureProp." and have spaces replaced by underscores. So, for example, the
- // configuration key "gestureProp.Palm_Width" refers to the "Palm Width" property.
- const std::string gesturePropPrefix = "gestureProp.";
- for (const std::string key : idcProperties.getKeysWithPrefix(gesturePropPrefix)) {
- std::string propertyName = key.substr(gesturePropPrefix.length());
- for (size_t i = 0; i < propertyName.length(); i++) {
- if (propertyName[i] == '_') {
- propertyName[i] = ' ';
- }
- }
-
- auto it = mProperties.find(propertyName);
- if (it != mProperties.end()) {
- it->second.trySetFromIdcProperty(idcProperties, key);
- } else {
- ALOGE("Gesture property \"%s\" specified in IDC file does not exist for this device.",
- propertyName.c_str());
- }
- }
-}
-
GesturesProp* PropertyProvider::createIntArrayProperty(const std::string& name, int* loc,
size_t count, const int* init) {
const auto [it, inserted] =
@@ -234,59 +211,6 @@
setValues(std::get<double*>(mDataPointer), values);
}
-namespace {
-
-// Helper to std::visit with lambdas.
-template <typename... V>
-struct Visitor : V... {};
-// explicit deduction guide (not needed as of C++20)
-template <typename... V>
-Visitor(V...) -> Visitor<V...>;
-
-} // namespace
-
-void GesturesProp::trySetFromIdcProperty(const android::PropertyMap& idcProperties,
- const std::string& propertyName) {
- if (mCount != 1) {
- ALOGE("Gesture property \"%s\" is an array, and so cannot be set in an IDC file.",
- mName.c_str());
- return;
- }
- bool parsedSuccessfully = false;
- Visitor setVisitor{
- [&](int*) {
- int32_t value;
- parsedSuccessfully = idcProperties.tryGetProperty(propertyName, value);
- if (parsedSuccessfully) {
- setIntValues({value});
- }
- },
- [&](GesturesPropBool*) {
- bool value;
- parsedSuccessfully = idcProperties.tryGetProperty(propertyName, value);
- if (parsedSuccessfully) {
- setBoolValues({value});
- }
- },
- [&](double*) {
- double value;
- parsedSuccessfully = idcProperties.tryGetProperty(propertyName, value);
- if (parsedSuccessfully) {
- setRealValues({value});
- }
- },
- [&](const char**) {
- ALOGE("Gesture property \"%s\" is a string, and so cannot be set in an IDC file.",
- mName.c_str());
- },
- };
- std::visit(setVisitor, mDataPointer);
-
- ALOGE_IF(!parsedSuccessfully, "Gesture property \"%s\" could set due to a type mismatch.",
- mName.c_str());
- return;
-}
-
template <typename T, typename U>
const std::vector<T> GesturesProp::getValues(U* dataPointer) const {
if (mGetter != nullptr) {
diff --git a/services/inputflinger/reader/mapper/gestures/PropertyProvider.h b/services/inputflinger/reader/mapper/gestures/PropertyProvider.h
index c7e0858..50451a3 100644
--- a/services/inputflinger/reader/mapper/gestures/PropertyProvider.h
+++ b/services/inputflinger/reader/mapper/gestures/PropertyProvider.h
@@ -22,7 +22,6 @@
#include <vector>
#include "include/gestures.h"
-#include "input/PropertyMap.h"
namespace android {
@@ -36,8 +35,6 @@
GesturesProp& getProperty(const std::string& name);
std::string dump() const;
- void loadPropertiesFromIdcFile(const PropertyMap& idcProperties);
-
// Methods to be called by the gestures library:
GesturesProp* createIntArrayProperty(const std::string& name, int* loc, size_t count,
const int* init);
@@ -86,9 +83,6 @@
// Setting string values isn't supported since we don't have a use case yet and the memory
// management adds additional complexity.
- void trySetFromIdcProperty(const android::PropertyMap& idcProperties,
- const std::string& propertyName);
-
private:
// Two type parameters are required for these methods, rather than one, due to the gestures
// library using its own bool type.
diff --git a/services/inputflinger/tests/InputDispatcher_test.cpp b/services/inputflinger/tests/InputDispatcher_test.cpp
index 3586a5e..e299643 100644
--- a/services/inputflinger/tests/InputDispatcher_test.cpp
+++ b/services/inputflinger/tests/InputDispatcher_test.cpp
@@ -3938,8 +3938,7 @@
public:
void SetUp() override {
InputDispatcherTest::SetUp();
- mDisplayInfos.clear();
- mWindowInfos.clear();
+ removeAllWindowsAndDisplays();
}
void addDisplayInfo(int displayId, const ui::Transform& transform) {
@@ -3955,6 +3954,11 @@
mDispatcher->onWindowInfosChanged(mWindowInfos, mDisplayInfos);
}
+ void removeAllWindowsAndDisplays() {
+ mDisplayInfos.clear();
+ mWindowInfos.clear();
+ }
+
// Set up a test scenario where the display has a scaled projection and there are two windows
// on the display.
std::pair<sp<FakeWindowHandle>, sp<FakeWindowHandle>> setupScaledDisplayScenario() {
@@ -3987,11 +3991,11 @@
std::vector<gui::WindowInfo> mWindowInfos;
};
-TEST_F(InputDispatcherDisplayProjectionTest, HitTestsInDisplaySpace) {
+TEST_F(InputDispatcherDisplayProjectionTest, HitTestCoordinateSpaceConsistency) {
auto [firstWindow, secondWindow] = setupScaledDisplayScenario();
// Send down to the first window. The point is represented in the display space. The point is
- // selected so that if the hit test was done with the transform applied to it, then it would
- // end up in the incorrect window.
+ // selected so that if the hit test was performed with the point and the bounds being in
+ // different coordinate spaces, the event would end up in the incorrect window.
NotifyMotionArgs downMotionArgs =
generateMotionArgs(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN,
ADISPLAY_ID_DEFAULT, {PointF{75, 55}});
@@ -4066,6 +4070,81 @@
EXPECT_EQ(80, event->getY(0));
}
+/** Ensure consistent behavior of InputDispatcher in all orientations. */
+class InputDispatcherDisplayOrientationFixture
+ : public InputDispatcherDisplayProjectionTest,
+ public ::testing::WithParamInterface<ui::Rotation> {};
+
+// This test verifies the touchable region of a window for all rotations of the display by tapping
+// in different locations on the display, specifically points close to the four corners of a
+// window.
+TEST_P(InputDispatcherDisplayOrientationFixture, HitTestInDifferentOrientations) {
+ constexpr static int32_t displayWidth = 400;
+ constexpr static int32_t displayHeight = 800;
+
+ std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
+
+ const auto rotation = GetParam();
+
+ // Set up the display with the specified rotation.
+ const bool isRotated = rotation == ui::ROTATION_90 || rotation == ui::ROTATION_270;
+ const int32_t logicalDisplayWidth = isRotated ? displayHeight : displayWidth;
+ const int32_t logicalDisplayHeight = isRotated ? displayWidth : displayHeight;
+ const ui::Transform displayTransform(ui::Transform::toRotationFlags(rotation),
+ logicalDisplayWidth, logicalDisplayHeight);
+ addDisplayInfo(ADISPLAY_ID_DEFAULT, displayTransform);
+
+ // Create a window with its bounds determined in the logical display.
+ const Rect frameInLogicalDisplay(100, 100, 200, 300);
+ const Rect frameInDisplay = displayTransform.inverse().transform(frameInLogicalDisplay);
+ sp<FakeWindowHandle> window =
+ sp<FakeWindowHandle>::make(application, mDispatcher, "Window", ADISPLAY_ID_DEFAULT);
+ window->setFrame(frameInDisplay, displayTransform);
+ addWindow(window);
+
+ // The following points in logical display space should be inside the window.
+ static const std::array<vec2, 4> insidePoints{
+ {{100, 100}, {199.99, 100}, {100, 299.99}, {199.99, 299.99}}};
+ for (const auto pointInsideWindow : insidePoints) {
+ const vec2 p = displayTransform.inverse().transform(pointInsideWindow);
+ const PointF pointInDisplaySpace{p.x, p.y};
+ const auto down = generateMotionArgs(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN,
+ ADISPLAY_ID_DEFAULT, {pointInDisplaySpace});
+ mDispatcher->notifyMotion(&down);
+ window->consumeMotionDown();
+
+ const auto up = generateMotionArgs(AMOTION_EVENT_ACTION_UP, AINPUT_SOURCE_TOUCHSCREEN,
+ ADISPLAY_ID_DEFAULT, {pointInDisplaySpace});
+ mDispatcher->notifyMotion(&up);
+ window->consumeMotionUp();
+ }
+
+ // The following points in logical display space should be outside the window.
+ static const std::array<vec2, 5> outsidePoints{
+ {{200, 100}, {100, 300}, {200, 300}, {100, 99.99}, {99.99, 100}}};
+ for (const auto pointOutsideWindow : outsidePoints) {
+ const vec2 p = displayTransform.inverse().transform(pointOutsideWindow);
+ const PointF pointInDisplaySpace{p.x, p.y};
+ const auto down = generateMotionArgs(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN,
+ ADISPLAY_ID_DEFAULT, {pointInDisplaySpace});
+ mDispatcher->notifyMotion(&down);
+
+ const auto up = generateMotionArgs(AMOTION_EVENT_ACTION_UP, AINPUT_SOURCE_TOUCHSCREEN,
+ ADISPLAY_ID_DEFAULT, {pointInDisplaySpace});
+ mDispatcher->notifyMotion(&up);
+ }
+ window->assertNoEvents();
+}
+
+// Run the precision tests for all rotations.
+INSTANTIATE_TEST_SUITE_P(InputDispatcherDisplayOrientationTests,
+ InputDispatcherDisplayOrientationFixture,
+ ::testing::Values(ui::ROTATION_0, ui::ROTATION_90, ui::ROTATION_180,
+ ui::ROTATION_270),
+ [](const testing::TestParamInfo<ui::Rotation>& testParamInfo) {
+ return ftl::enum_string(testParamInfo.param);
+ });
+
using TransferFunction = std::function<bool(const std::unique_ptr<InputDispatcher>& dispatcher,
sp<IBinder>, sp<IBinder>)>;
diff --git a/services/inputflinger/tests/InputReader_test.cpp b/services/inputflinger/tests/InputReader_test.cpp
index 9732e8d..711cfbf 100644
--- a/services/inputflinger/tests/InputReader_test.cpp
+++ b/services/inputflinger/tests/InputReader_test.cpp
@@ -6927,9 +6927,11 @@
// four times the resolution of the display in the Y axis.
prepareButtons();
mFakeEventHub->addAbsoluteAxis(EVENTHUB_ID, ABS_X, PRECISION_RAW_X_MIN, PRECISION_RAW_X_MAX,
- 0, 0);
+ PRECISION_RAW_X_FLAT, PRECISION_RAW_X_FUZZ,
+ PRECISION_RAW_X_RES);
mFakeEventHub->addAbsoluteAxis(EVENTHUB_ID, ABS_Y, PRECISION_RAW_Y_MIN, PRECISION_RAW_Y_MAX,
- 0, 0);
+ PRECISION_RAW_Y_FLAT, PRECISION_RAW_Y_FUZZ,
+ PRECISION_RAW_Y_RES);
}
static const int32_t PRECISION_RAW_X_MIN = TouchInputMapperTest::RAW_X_MIN;
@@ -6937,6 +6939,15 @@
static const int32_t PRECISION_RAW_Y_MIN = TouchInputMapperTest::RAW_Y_MIN;
static const int32_t PRECISION_RAW_Y_MAX = PRECISION_RAW_Y_MIN + DISPLAY_HEIGHT * 4 - 1;
+ static const int32_t PRECISION_RAW_X_RES = 50; // units per millimeter
+ static const int32_t PRECISION_RAW_Y_RES = 100; // units per millimeter
+
+ static const int32_t PRECISION_RAW_X_FLAT = 16;
+ static const int32_t PRECISION_RAW_Y_FLAT = 32;
+
+ static const int32_t PRECISION_RAW_X_FUZZ = 4;
+ static const int32_t PRECISION_RAW_Y_FUZZ = 8;
+
static const std::array<Point, 4> kRawCorners;
};
@@ -7094,6 +7105,41 @@
}
}
+TEST_P(TouchscreenPrecisionTestsFixture, MotionRangesAreOrientedInRotatedDisplay) {
+ const ui::Rotation displayRotation = GetParam();
+
+ addConfigurationProperty("touch.deviceType", "touchScreen");
+ prepareDisplay(displayRotation);
+
+ __attribute__((unused)) SingleTouchInputMapper& mapper =
+ addMapperAndConfigure<SingleTouchInputMapper>();
+
+ const InputDeviceInfo deviceInfo = mDevice->getDeviceInfo();
+ // MotionRanges use display pixels as their units
+ const auto* xRange = deviceInfo.getMotionRange(AMOTION_EVENT_AXIS_X, AINPUT_SOURCE_TOUCHSCREEN);
+ const auto* yRange = deviceInfo.getMotionRange(AMOTION_EVENT_AXIS_Y, AINPUT_SOURCE_TOUCHSCREEN);
+
+ // The MotionRanges should be oriented in the rotated display's coordinate space
+ const bool displayRotated =
+ displayRotation == ui::ROTATION_90 || displayRotation == ui::ROTATION_270;
+
+ constexpr float MAX_X = 479.5;
+ constexpr float MAX_Y = 799.75;
+ EXPECT_EQ(xRange->min, 0.f);
+ EXPECT_EQ(yRange->min, 0.f);
+ EXPECT_EQ(xRange->max, displayRotated ? MAX_Y : MAX_X);
+ EXPECT_EQ(yRange->max, displayRotated ? MAX_X : MAX_Y);
+
+ EXPECT_EQ(xRange->flat, 8.f);
+ EXPECT_EQ(yRange->flat, 8.f);
+
+ EXPECT_EQ(xRange->fuzz, 2.f);
+ EXPECT_EQ(yRange->fuzz, 2.f);
+
+ EXPECT_EQ(xRange->resolution, 25.f); // pixels per millimeter
+ EXPECT_EQ(yRange->resolution, 25.f); // pixels per millimeter
+}
+
// Run the precision tests for all rotations.
INSTANTIATE_TEST_SUITE_P(TouchscreenPrecisionTests, TouchscreenPrecisionTestsFixture,
::testing::Values(ui::ROTATION_0, ui::ROTATION_90, ui::ROTATION_180,
diff --git a/services/inputflinger/tests/PropertyProvider_test.cpp b/services/inputflinger/tests/PropertyProvider_test.cpp
index 8a40e78..42a6a9f 100644
--- a/services/inputflinger/tests/PropertyProvider_test.cpp
+++ b/services/inputflinger/tests/PropertyProvider_test.cpp
@@ -18,7 +18,6 @@
#include <gmock/gmock.h>
#include <gtest/gtest.h>
-#include "TestConstants.h"
#include "include/gestures.h"
namespace android {
@@ -284,68 +283,4 @@
EXPECT_FALSE(mProvider.hasProperty("Foo"));
}
-class PropertyProviderIdcLoadingTest : public testing::Test {
-protected:
- void SetUp() override {
- int initialInt = 0;
- GesturesPropBool initialBool = false;
- double initialReal = 0.0;
- gesturePropProvider.create_int_fn(&mProvider, "An Integer", &mIntData, 1, &initialInt);
- gesturePropProvider.create_bool_fn(&mProvider, "A Boolean", &mBoolData, 1, &initialBool);
- gesturePropProvider.create_real_fn(&mProvider, "A Real", &mRealData, 1, &initialReal);
- }
-
- PropertyProvider mProvider;
-
- int mIntData;
- GesturesPropBool mBoolData;
- double mRealData;
-};
-
-TEST_F(PropertyProviderIdcLoadingTest, AllCorrect) {
- PropertyMap idcProps;
- idcProps.addProperty("gestureProp.An_Integer", "42");
- idcProps.addProperty("gestureProp.A_Boolean", "1");
- idcProps.addProperty("gestureProp.A_Real", "3.14159");
-
- mProvider.loadPropertiesFromIdcFile(idcProps);
- EXPECT_THAT(mProvider.getProperty("An Integer").getIntValues(), ElementsAre(42));
- EXPECT_THAT(mProvider.getProperty("A Boolean").getBoolValues(), ElementsAre(true));
- EXPECT_NEAR(mProvider.getProperty("A Real").getRealValues()[0], 3.14159, EPSILON);
-}
-
-TEST_F(PropertyProviderIdcLoadingTest, InvalidPropsIgnored) {
- int intArrayData[2];
- int initialInts[2] = {0, 1};
- gesturePropProvider.create_int_fn(&mProvider, "Two Integers", intArrayData, 2, initialInts);
-
- PropertyMap idcProps;
- // Wrong type
- idcProps.addProperty("gestureProp.An_Integer", "37.25");
- // Wrong size
- idcProps.addProperty("gestureProp.Two_Integers", "42");
- // Doesn't exist
- idcProps.addProperty("gestureProp.Some_Nonexistent_Property", "1");
- // A valid assignment that should still be applied despite the others being invalid
- idcProps.addProperty("gestureProp.A_Real", "3.14159");
-
- mProvider.loadPropertiesFromIdcFile(idcProps);
- EXPECT_THAT(mProvider.getProperty("An Integer").getIntValues(), ElementsAre(0));
- EXPECT_THAT(mProvider.getProperty("Two Integers").getIntValues(), ElementsAre(0, 1));
- EXPECT_FALSE(mProvider.hasProperty("Some Nonexistent Property"));
- EXPECT_NEAR(mProvider.getProperty("A Real").getRealValues()[0], 3.14159, EPSILON);
-}
-
-TEST_F(PropertyProviderIdcLoadingTest, FunkyName) {
- int data;
- int initialData = 0;
- gesturePropProvider.create_int_fn(&mProvider, " I lOvE sNAKes ", &data, 1, &initialData);
-
- PropertyMap idcProps;
- idcProps.addProperty("gestureProp.__I_lOvE_sNAKes_", "42");
-
- mProvider.loadPropertiesFromIdcFile(idcProps);
- EXPECT_THAT(mProvider.getProperty(" I lOvE sNAKes ").getIntValues(), ElementsAre(42));
-}
-
} // namespace android
diff --git a/services/inputflinger/tests/TestConstants.h b/services/inputflinger/tests/TestConstants.h
index ad48b0f..27881f6 100644
--- a/services/inputflinger/tests/TestConstants.h
+++ b/services/inputflinger/tests/TestConstants.h
@@ -16,10 +16,6 @@
#pragma once
-#include <chrono>
-
-#include <utils/Timers.h>
-
namespace android {
using std::chrono_literals::operator""ms;
diff --git a/services/surfaceflinger/FrontEnd/LayerCreationArgs.cpp b/services/surfaceflinger/FrontEnd/LayerCreationArgs.cpp
index 6659825..5efa394 100644
--- a/services/surfaceflinger/FrontEnd/LayerCreationArgs.cpp
+++ b/services/surfaceflinger/FrontEnd/LayerCreationArgs.cpp
@@ -65,6 +65,10 @@
}
}
+LayerCreationArgs::LayerCreationArgs(std::optional<uint32_t> id, bool internalLayer)
+ : LayerCreationArgs(nullptr, nullptr, /*name=*/"", /*flags=*/0, /*metadata=*/{}, id,
+ internalLayer) {}
+
LayerCreationArgs::LayerCreationArgs(const LayerCreationArgs& args)
: LayerCreationArgs(args.flinger, args.client, args.name, args.flags, args.metadata) {}
diff --git a/services/surfaceflinger/FrontEnd/LayerCreationArgs.h b/services/surfaceflinger/FrontEnd/LayerCreationArgs.h
index 2cd6b55..8341e1d 100644
--- a/services/surfaceflinger/FrontEnd/LayerCreationArgs.h
+++ b/services/surfaceflinger/FrontEnd/LayerCreationArgs.h
@@ -41,6 +41,8 @@
LayerCreationArgs(android::SurfaceFlinger*, sp<android::Client>, std::string name,
uint32_t flags, gui::LayerMetadata, std::optional<uint32_t> id = std::nullopt,
bool internalLayer = false);
+ LayerCreationArgs(std::optional<uint32_t> id, bool internalLayer = false);
+
LayerCreationArgs(const LayerCreationArgs&);
android::SurfaceFlinger* flinger;
@@ -56,6 +58,8 @@
wp<IBinder> parentHandle = nullptr;
wp<IBinder> mirrorLayerHandle = nullptr;
ui::LayerStack layerStackToMirror = ui::INVALID_LAYER_STACK;
+ uint32_t parentId = UNASSIGNED_LAYER_ID;
+ uint32_t layerIdToMirror = UNASSIGNED_LAYER_ID;
};
} // namespace android::surfaceflinger
diff --git a/services/surfaceflinger/FrontEnd/LayerLifecycleManager.cpp b/services/surfaceflinger/FrontEnd/LayerLifecycleManager.cpp
index 33cc429..fe42422 100644
--- a/services/surfaceflinger/FrontEnd/LayerLifecycleManager.cpp
+++ b/services/surfaceflinger/FrontEnd/LayerLifecycleManager.cpp
@@ -20,8 +20,7 @@
#define LOG_TAG "LayerLifecycleManager"
#include "LayerLifecycleManager.h"
-#include "Layer.h" // temporarily needed for LayerHandle
-#include "LayerHandle.h"
+#include "Client.h" // temporarily needed for LayerCreationArgs
#include "LayerLog.h"
#include "SwapErase.h"
@@ -167,7 +166,7 @@
for (const auto& transaction : transactions) {
for (const auto& resolvedComposerState : transaction.states) {
const auto& clientState = resolvedComposerState.state;
- uint32_t layerId = LayerHandle::getLayerId(clientState.surface);
+ uint32_t layerId = resolvedComposerState.layerId;
if (layerId == UNASSIGNED_LAYER_ID) {
ALOGW("%s Handle %p is not valid", __func__, clientState.surface.get());
continue;
@@ -175,15 +174,14 @@
RequestedLayerState* layer = getLayerFromId(layerId);
if (layer == nullptr) {
- LOG_ALWAYS_FATAL("%s Layer with handle %p (layerid=%d) not found", __func__,
- clientState.surface.get(), layerId);
+ LOG_ALWAYS_FATAL("%s Layer with layerid=%d not found", __func__, layerId);
continue;
}
if (!layer->handleAlive) {
- LOG_ALWAYS_FATAL("%s Layer's handle %p (layerid=%d) is not alive. Possible out of "
+ LOG_ALWAYS_FATAL("%s Layer's with layerid=%d) is not alive. Possible out of "
"order LayerLifecycleManager updates",
- __func__, clientState.surface.get(), layerId);
+ __func__, layerId);
continue;
}
@@ -198,13 +196,11 @@
if (layer->what & layer_state_t::eBackgroundColorChanged) {
if (layer->bgColorLayerId == UNASSIGNED_LAYER_ID && layer->bgColor.a != 0) {
- LayerCreationArgs backgroundLayerArgs{nullptr,
- nullptr,
- layer->name + "BackgroundColorLayer",
- ISurfaceComposerClient::eFXSurfaceEffect,
- {},
- layer->id,
- /*internalLayer=*/true};
+ LayerCreationArgs backgroundLayerArgs(layer->id,
+ /*internalLayer=*/true);
+ backgroundLayerArgs.parentId = layer->id;
+ backgroundLayerArgs.name = layer->name + "BackgroundColorLayer";
+ backgroundLayerArgs.flags = ISurfaceComposerClient::eFXSurfaceEffect;
std::vector<std::unique_ptr<RequestedLayerState>> newLayers;
newLayers.emplace_back(
std::make_unique<RequestedLayerState>(backgroundLayerArgs));
diff --git a/services/surfaceflinger/FrontEnd/RequestedLayerState.cpp b/services/surfaceflinger/FrontEnd/RequestedLayerState.cpp
index e2cbe28..a5fdaf4 100644
--- a/services/surfaceflinger/FrontEnd/RequestedLayerState.cpp
+++ b/services/surfaceflinger/FrontEnd/RequestedLayerState.cpp
@@ -24,7 +24,6 @@
#include "Layer.h"
#include "LayerCreationArgs.h"
-#include "LayerHandle.h"
#include "LayerLog.h"
#include "RequestedLayerState.h"
@@ -33,14 +32,6 @@
using namespace ftl::flag_operators;
namespace {
-uint32_t getLayerIdFromSurfaceControl(sp<SurfaceControl> surfaceControl) {
- if (!surfaceControl) {
- return UNASSIGNED_LAYER_ID;
- }
-
- return LayerHandle::getLayerId(surfaceControl->getHandle());
-}
-
std::string layerIdToString(uint32_t layerId) {
return layerId == UNASSIGNED_LAYER_ID ? "none" : std::to_string(layerId);
}
@@ -64,17 +55,17 @@
layerCreationFlags(args.flags),
textureName(args.textureName),
ownerUid(args.ownerUid),
- ownerPid(args.ownerPid) {
+ ownerPid(args.ownerPid),
+ parentId(args.parentId),
+ layerIdToMirror(args.layerIdToMirror) {
layerId = static_cast<int32_t>(args.sequence);
changes |= RequestedLayerState::Changes::Created;
metadata.merge(args.metadata);
changes |= RequestedLayerState::Changes::Metadata;
handleAlive = true;
- parentId = LayerHandle::getLayerId(args.parentHandle.promote());
- if (args.parentHandle != nullptr) {
+ if (parentId != UNASSIGNED_LAYER_ID) {
canBeRoot = false;
}
- layerIdToMirror = LayerHandle::getLayerId(args.mirrorLayerHandle.promote());
if (layerIdToMirror != UNASSIGNED_LAYER_ID) {
changes |= RequestedLayerState::Changes::Mirror;
} else if (args.layerStackToMirror != ui::INVALID_LAYER_STACK) {
@@ -209,7 +200,7 @@
}
if (clientState.what & layer_state_t::eReparent) {
changes |= RequestedLayerState::Changes::Parent;
- parentId = getLayerIdFromSurfaceControl(clientState.parentSurfaceControlForChild);
+ parentId = resolvedComposerState.parentId;
parentSurfaceControlForChild = nullptr;
// Once a layer has be reparented, it cannot be placed at the root. It sounds odd
// but thats the existing logic and until we make this behavior more explicit, we need
@@ -218,7 +209,7 @@
}
if (clientState.what & layer_state_t::eRelativeLayerChanged) {
changes |= RequestedLayerState::Changes::RelativeParent;
- relativeParentId = getLayerIdFromSurfaceControl(clientState.relativeLayerSurfaceControl);
+ relativeParentId = resolvedComposerState.relativeParentId;
isRelativeOf = true;
relativeLayerSurfaceControl = nullptr;
}
@@ -235,10 +226,8 @@
changes |= RequestedLayerState::Changes::RelativeParent;
}
if (clientState.what & layer_state_t::eInputInfoChanged) {
- wp<IBinder>& touchableRegionCropHandle =
- windowInfoHandle->editInfo()->touchableRegionCropHandle;
- touchCropId = LayerHandle::getLayerId(touchableRegionCropHandle.promote());
- touchableRegionCropHandle.clear();
+ touchCropId = resolvedComposerState.touchCropId;
+ windowInfoHandle->editInfo()->touchableRegionCropHandle.clear();
}
if (clientState.what & layer_state_t::eStretchChanged) {
stretchEffect.sanitize();
diff --git a/services/surfaceflinger/FrontEnd/RequestedLayerState.h b/services/surfaceflinger/FrontEnd/RequestedLayerState.h
index 6f5485d..216e95f 100644
--- a/services/surfaceflinger/FrontEnd/RequestedLayerState.h
+++ b/services/surfaceflinger/FrontEnd/RequestedLayerState.h
@@ -105,17 +105,17 @@
std::shared_ptr<renderengine::ExternalTexture> externalTexture;
gui::GameMode gameMode;
scheduler::LayerInfo::FrameRate requestedFrameRate;
- ui::LayerStack layerStackToMirror = ui::INVALID_LAYER_STACK;
+ uint32_t parentId = UNASSIGNED_LAYER_ID;
+ uint32_t relativeParentId = UNASSIGNED_LAYER_ID;
uint32_t layerIdToMirror = UNASSIGNED_LAYER_ID;
+ ui::LayerStack layerStackToMirror = ui::INVALID_LAYER_STACK;
+ uint32_t touchCropId = UNASSIGNED_LAYER_ID;
+ uint32_t bgColorLayerId = UNASSIGNED_LAYER_ID;
// book keeping states
bool handleAlive = true;
bool isRelativeOf = false;
- uint32_t parentId = UNASSIGNED_LAYER_ID;
- uint32_t relativeParentId = UNASSIGNED_LAYER_ID;
std::vector<uint32_t> mirrorIds{};
- uint32_t touchCropId = UNASSIGNED_LAYER_ID;
- uint32_t bgColorLayerId = UNASSIGNED_LAYER_ID;
ftl::Flags<RequestedLayerState::Changes> changes;
bool bgColorLayer = false;
};
diff --git a/services/surfaceflinger/Scheduler/Scheduler.cpp b/services/surfaceflinger/Scheduler/Scheduler.cpp
index f18dfdc..6e33272 100644
--- a/services/surfaceflinger/Scheduler/Scheduler.cpp
+++ b/services/surfaceflinger/Scheduler/Scheduler.cpp
@@ -402,6 +402,7 @@
}
void Scheduler::resyncAllToHardwareVsync(bool allowToEnable) {
+ ATRACE_CALL();
std::scoped_lock lock(mDisplayLock);
ftl::FakeGuard guard(kMainThreadContext);
diff --git a/services/surfaceflinger/Scheduler/Scheduler.h b/services/surfaceflinger/Scheduler/Scheduler.h
index 62a5fb2..74547d5 100644
--- a/services/surfaceflinger/Scheduler/Scheduler.h
+++ b/services/surfaceflinger/Scheduler/Scheduler.h
@@ -165,7 +165,7 @@
void setDuration(ConnectionHandle, std::chrono::nanoseconds workDuration,
std::chrono::nanoseconds readyDuration);
- const VsyncModulator& vsyncModulator() const { return *mVsyncModulator; }
+ VsyncModulator& vsyncModulator() { return *mVsyncModulator; }
// In some cases, we should only modulate for the pacesetter display. In those
// cases, the caller should pass in the relevant display, and the method
diff --git a/services/surfaceflinger/Scheduler/VsyncModulator.cpp b/services/surfaceflinger/Scheduler/VsyncModulator.cpp
index c9af4c2..586357f 100644
--- a/services/surfaceflinger/Scheduler/VsyncModulator.cpp
+++ b/services/surfaceflinger/Scheduler/VsyncModulator.cpp
@@ -187,9 +187,9 @@
static_cast<void>(updateVsyncConfigLocked());
}
-bool VsyncModulator::isVsyncConfigDefault() const {
+bool VsyncModulator::isVsyncConfigEarly() const {
std::lock_guard<std::mutex> lock(mMutex);
- return getNextVsyncConfigType() == VsyncConfigType::Late;
+ return getNextVsyncConfigType() != VsyncConfigType::Late;
}
} // namespace android::scheduler
diff --git a/services/surfaceflinger/Scheduler/VsyncModulator.h b/services/surfaceflinger/Scheduler/VsyncModulator.h
index dc4dafd..be0d334 100644
--- a/services/surfaceflinger/Scheduler/VsyncModulator.h
+++ b/services/surfaceflinger/Scheduler/VsyncModulator.h
@@ -53,8 +53,12 @@
explicit VsyncModulator(const VsyncConfigSet&, Now = Clock::now);
+ bool isVsyncConfigEarly() const EXCLUDES(mMutex);
+
VsyncConfig getVsyncConfig() const EXCLUDES(mMutex);
+ void cancelRefreshRateChange() { mRefreshRateChangePending = false; }
+
[[nodiscard]] VsyncConfig setVsyncConfigSet(const VsyncConfigSet&) EXCLUDES(mMutex);
// Changes offsets in response to transaction flags or commit.
@@ -72,8 +76,6 @@
[[nodiscard]] VsyncConfigOpt onDisplayRefresh(bool usedGpuComposition);
- [[nodiscard]] bool isVsyncConfigDefault() const;
-
protected:
// Called from unit tests as well
void binderDied(const wp<IBinder>&) override EXCLUDES(mMutex);
diff --git a/services/surfaceflinger/SurfaceFlinger.cpp b/services/surfaceflinger/SurfaceFlinger.cpp
index 0bdede8..e902a3d 100644
--- a/services/surfaceflinger/SurfaceFlinger.cpp
+++ b/services/surfaceflinger/SurfaceFlinger.cpp
@@ -292,6 +292,13 @@
displayHdrCapabilities.getDesiredMinLuminance()};
}
+uint32_t getLayerIdFromSurfaceControl(sp<SurfaceControl> surfaceControl) {
+ if (!surfaceControl) {
+ return UNASSIGNED_LAYER_ID;
+ }
+ return LayerHandle::getLayerId(surfaceControl->getHandle());
+}
+
} // namespace anonymous
// ---------------------------------------------------------------------------
@@ -497,14 +504,13 @@
// the window manager died on us. prepare its eulogy.
mBootFinished = false;
- // Sever the link to inputflinger since it's gone as well.
- static_cast<void>(mScheduler->schedule(
- [this] { mInputFlinger.clear(); }));
+ static_cast<void>(mScheduler->schedule([this]() FTL_FAKE_GUARD(kMainThreadContext) {
+ // Sever the link to inputflinger since it's gone as well.
+ mInputFlinger.clear();
- // restore initial conditions (default device unblank, etc)
- initializeDisplays();
+ initializeDisplays();
+ }));
- // restart the boot-animation
startBootAnim();
}
@@ -873,7 +879,9 @@
mDrawingState = mCurrentState;
onActiveDisplayChangedLocked(nullptr, *display);
- initializeDisplays();
+
+ static_cast<void>(mScheduler->schedule(
+ [this]() FTL_FAKE_GUARD(kMainThreadContext) { initializeDisplays(); }));
mPowerAdvisor->init();
@@ -3485,7 +3493,7 @@
// TODO(b/175678251) Call a listener instead.
if (currentState.physical->hwcDisplayId == getHwComposer().getPrimaryHwcDisplayId()) {
- updateActiveDisplayVsyncLocked(*display);
+ resetPhaseConfiguration(display->getActiveMode().fps);
}
}
return;
@@ -3519,9 +3527,11 @@
}
}
-void SurfaceFlinger::updateActiveDisplayVsyncLocked(const DisplayDevice& activeDisplay) {
+void SurfaceFlinger::resetPhaseConfiguration(Fps refreshRate) {
+ // Cancel the pending refresh rate change, if any, before updating the phase configuration.
+ mScheduler->vsyncModulator().cancelRefreshRateChange();
+
mVsyncConfiguration->reset();
- const Fps refreshRate = activeDisplay.getActiveMode().fps;
updatePhaseConfiguration(refreshRate);
mRefreshRateStats->setRefreshRate(refreshRate);
}
@@ -4061,7 +4071,7 @@
return !mLayersWithQueuedFrames.empty() && newDataLatched;
}
-status_t SurfaceFlinger::addClientLayer(const LayerCreationArgs& args, const sp<IBinder>& handle,
+status_t SurfaceFlinger::addClientLayer(LayerCreationArgs& args, const sp<IBinder>& handle,
const sp<Layer>& layer, const wp<Layer>& parent,
uint32_t* outTransformHint) {
if (mNumLayers >= MAX_LAYERS) {
@@ -4091,7 +4101,8 @@
if (outTransformHint) {
*outTransformHint = mActiveDisplayTransformHint;
}
-
+ args.parentId = LayerHandle::getLayerId(args.parentHandle.promote());
+ args.layerIdToMirror = LayerHandle::getLayerId(args.mirrorLayerHandle.promote());
{
std::scoped_lock<std::mutex> lock(mCreatedLayersLock);
mCreatedLayers.emplace_back(layer, parent, args.addToRoot);
@@ -4119,6 +4130,7 @@
ATRACE_INT("mTransactionFlags", transactionFlags);
if (const bool scheduled = transactionFlags & mask; !scheduled) {
+ mScheduler->resync();
scheduleCommit(frameHint);
} else if (frameHint == FrameHint::kActive) {
// Even if the next frame is already scheduled, we should reset the idle timer
@@ -4261,7 +4273,7 @@
bool SurfaceFlinger::applyTransactions(std::vector<TransactionState>& transactions,
VsyncId vsyncId) {
- Mutex::Autolock _l(mStateLock);
+ Mutex::Autolock lock(mStateLock);
return applyTransactionsLocked(transactions, vsyncId);
}
@@ -4342,9 +4354,8 @@
// We don't want to latch unsignaled if are in early / client composition
// as it leads to jank due to RenderEngine waiting for unsignaled buffer
// or window animations being slow.
- const auto isDefaultVsyncConfig = mScheduler->vsyncModulator().isVsyncConfigDefault();
- if (!isDefaultVsyncConfig) {
- ALOGV("%s: false (LatchUnsignaledConfig::AutoSingleLayer; !isDefaultVsyncConfig)",
+ if (mScheduler->vsyncModulator().isVsyncConfigEarly()) {
+ ALOGV("%s: false (LatchUnsignaledConfig::AutoSingleLayer; isVsyncConfigEarly)",
__func__);
return false;
}
@@ -4423,6 +4434,21 @@
layerName.c_str(), transactionId);
mBufferCountTracker.increment(resolvedState.state.surface->localBinder());
}
+ resolvedState.layerId = LayerHandle::getLayerId(resolvedState.state.surface);
+ if (resolvedState.state.what & layer_state_t::eReparent) {
+ resolvedState.parentId =
+ getLayerIdFromSurfaceControl(resolvedState.state.parentSurfaceControlForChild);
+ }
+ if (resolvedState.state.what & layer_state_t::eRelativeLayerChanged) {
+ resolvedState.relativeParentId =
+ getLayerIdFromSurfaceControl(resolvedState.state.relativeLayerSurfaceControl);
+ }
+ if (resolvedState.state.what & layer_state_t::eInputInfoChanged) {
+ wp<IBinder>& touchableRegionCropHandle =
+ resolvedState.state.windowInfoHandle->editInfo()->touchableRegionCropHandle;
+ resolvedState.touchCropId =
+ LayerHandle::getLayerId(touchableRegionCropHandle.promote());
+ }
}
TransactionState state{frameTimelineInfo,
@@ -4547,7 +4573,7 @@
bool SurfaceFlinger::applyAndCommitDisplayTransactionStates(
std::vector<TransactionState>& transactions) {
- Mutex::Autolock _l(mStateLock);
+ Mutex::Autolock lock(mStateLock);
bool needsTraversal = false;
uint32_t transactionFlags = 0;
for (auto& transaction : transactions) {
@@ -5285,8 +5311,8 @@
setTransactionFlags(eTransactionFlushNeeded);
}
-void SurfaceFlinger::onInitializeDisplays() {
- const auto display = getDefaultDisplayDeviceLocked();
+void SurfaceFlinger::initializeDisplays() {
+ const auto display = FTL_FAKE_GUARD(mStateLock, getDefaultDisplayDeviceLocked());
if (!display) return;
const sp<IBinder> token = display->getDisplayToken().promote();
@@ -5294,13 +5320,13 @@
TransactionState state;
state.inputWindowCommands = mInputWindowCommands;
- nsecs_t now = systemTime();
+ const nsecs_t now = systemTime();
state.desiredPresentTime = now;
state.postTime = now;
state.permissions = layer_state_t::ACCESS_SURFACE_FLINGER;
state.originPid = mPid;
state.originUid = static_cast<int>(getuid());
- uint64_t transactionId = (((uint64_t)mPid) << 32) | mUniqueTransactionId++;
+ const uint64_t transactionId = (static_cast<uint64_t>(mPid) << 32) | mUniqueTransactionId++;
state.id = transactionId;
// reset screen orientation and use primary layer stack
@@ -5320,21 +5346,16 @@
std::vector<TransactionState> transactions;
transactions.emplace_back(state);
- // It should be on the main thread, apply it directly.
if (mLegacyFrontEndEnabled) {
- applyTransactionsLocked(transactions, /*vsyncId=*/{0});
+ applyTransactions(transactions, VsyncId{0});
} else {
applyAndCommitDisplayTransactionStates(transactions);
}
- setPowerModeInternal(display, hal::PowerMode::ON);
-}
-
-void SurfaceFlinger::initializeDisplays() {
- // Async since we may be called from the main thread.
- static_cast<void>(mScheduler->schedule(
- [this]() FTL_FAKE_GUARD(mStateLock)
- FTL_FAKE_GUARD(kMainThreadContext) { onInitializeDisplays(); }));
+ {
+ ftl::FakeGuard guard(mStateLock);
+ setPowerModeInternal(display, hal::PowerMode::ON);
+ }
}
void SurfaceFlinger::setPowerModeInternal(const sp<DisplayDevice>& display, hal::PowerMode mode) {
@@ -7721,14 +7742,20 @@
const DisplayDevice& activeDisplay) {
ATRACE_CALL();
+ // For the first display activated during boot, there is no need to force setDesiredActiveMode,
+ // because DM is about to send its policy via setDesiredDisplayModeSpecs.
+ bool forceApplyPolicy = false;
+
if (inactiveDisplayPtr) {
inactiveDisplayPtr->getCompositionDisplay()->setLayerCachingTexturePoolEnabled(false);
+ forceApplyPolicy = true;
}
mActiveDisplayId = activeDisplay.getPhysicalId();
activeDisplay.getCompositionDisplay()->setLayerCachingTexturePoolEnabled(true);
- updateActiveDisplayVsyncLocked(activeDisplay);
+ resetPhaseConfiguration(activeDisplay.getActiveMode().fps);
+
mScheduler->setModeChangePending(false);
mScheduler->setPacesetterDisplay(mActiveDisplayId);
@@ -7739,8 +7766,8 @@
// that case, its preferred mode has not been propagated to HWC (via setDesiredActiveMode). In
// either case, the Scheduler's cachedModeChangedParams must be initialized to the newly active
// mode, and the kernel idle timer of the newly active display must be toggled.
- constexpr bool kForce = true;
- applyRefreshRateSelectorPolicy(mActiveDisplayId, activeDisplay.refreshRateSelector(), kForce);
+ applyRefreshRateSelectorPolicy(mActiveDisplayId, activeDisplay.refreshRateSelector(),
+ forceApplyPolicy);
}
status_t SurfaceFlinger::addWindowInfosListener(
diff --git a/services/surfaceflinger/SurfaceFlinger.h b/services/surfaceflinger/SurfaceFlinger.h
index 338531f..63d54bc 100644
--- a/services/surfaceflinger/SurfaceFlinger.h
+++ b/services/surfaceflinger/SurfaceFlinger.h
@@ -737,6 +737,8 @@
void updateCursorAsync();
void initScheduler(const sp<const DisplayDevice>&) REQUIRES(kMainThreadContext, mStateLock);
+
+ void resetPhaseConfiguration(Fps) REQUIRES(mStateLock, kMainThreadContext);
void updatePhaseConfiguration(Fps) REQUIRES(mStateLock);
/*
@@ -818,7 +820,7 @@
void markLayerPendingRemovalLocked(const sp<Layer>& layer);
// add a layer to SurfaceFlinger
- status_t addClientLayer(const LayerCreationArgs& args, const sp<IBinder>& handle,
+ status_t addClientLayer(LayerCreationArgs& args, const sp<IBinder>& handle,
const sp<Layer>& layer, const wp<Layer>& parentLayer,
uint32_t* outTransformHint);
@@ -855,8 +857,7 @@
*/
// Called during boot, and restart after system_server death.
- void initializeDisplays();
- void onInitializeDisplays() REQUIRES(mStateLock, kMainThreadContext);
+ void initializeDisplays() REQUIRES(kMainThreadContext);
sp<const DisplayDevice> getDisplayDeviceLocked(const wp<IBinder>& displayToken) const
REQUIRES(mStateLock) {
@@ -1121,9 +1122,6 @@
std::chrono::nanoseconds presentLatency);
int getMaxAcquiredBufferCountForRefreshRate(Fps refreshRate) const;
- void updateActiveDisplayVsyncLocked(const DisplayDevice& activeDisplay)
- REQUIRES(mStateLock, kMainThreadContext);
-
bool isHdrLayer(const frontend::LayerSnapshot& snapshot) const;
ui::Rotation getPhysicalDisplayOrientation(DisplayId, bool isPrimary) const
diff --git a/services/surfaceflinger/TransactionState.h b/services/surfaceflinger/TransactionState.h
index 40d06a8..2daea25 100644
--- a/services/surfaceflinger/TransactionState.h
+++ b/services/surfaceflinger/TransactionState.h
@@ -20,6 +20,7 @@
#include <memory>
#include <mutex>
#include <vector>
+#include "FrontEnd/LayerCreationArgs.h"
#include "renderengine/ExternalTexture.h"
#include <gui/LayerState.h>
@@ -39,6 +40,10 @@
ResolvedComposerState() = default;
ResolvedComposerState(ComposerState&& source) { state = std::move(source.state); }
std::shared_ptr<renderengine::ExternalTexture> externalTexture;
+ uint32_t layerId = UNASSIGNED_LAYER_ID;
+ uint32_t parentId = UNASSIGNED_LAYER_ID;
+ uint32_t relativeParentId = UNASSIGNED_LAYER_ID;
+ uint32_t touchCropId = UNASSIGNED_LAYER_ID;
};
struct TransactionState {
diff --git a/services/surfaceflinger/fuzzer/surfaceflinger_fuzzers_utils.h b/services/surfaceflinger/fuzzer/surfaceflinger_fuzzers_utils.h
index f27f53b..72cecc9 100644
--- a/services/surfaceflinger/fuzzer/surfaceflinger_fuzzers_utils.h
+++ b/services/surfaceflinger/fuzzer/surfaceflinger_fuzzers_utils.h
@@ -402,9 +402,8 @@
SurfaceFlinger *flinger() { return mFlinger.get(); }
scheduler::TestableScheduler *scheduler() { return mScheduler; }
- // Allow reading display state without locking, as if called on the SF main thread.
- auto onInitializeDisplays() NO_THREAD_SAFETY_ANALYSIS {
- return mFlinger->onInitializeDisplays();
+ void initializeDisplays() {
+ FTL_FAKE_GUARD(kMainThreadContext, mFlinger->initializeDisplays());
}
void setGlobalShadowSettings(FuzzedDataProvider *fdp) {
@@ -542,7 +541,7 @@
mFlinger->createDisplay(String8(fdp->ConsumeRandomLengthString().c_str()),
fdp->ConsumeBool());
- onInitializeDisplays();
+ initializeDisplays();
mFlinger->getPhysicalDisplayToken(physicalDisplayId);
mFlinger->mStartPropertySetThread =
diff --git a/services/surfaceflinger/tests/unittests/Android.bp b/services/surfaceflinger/tests/unittests/Android.bp
index 012a4ad..df3ffd2 100644
--- a/services/surfaceflinger/tests/unittests/Android.bp
+++ b/services/surfaceflinger/tests/unittests/Android.bp
@@ -107,9 +107,9 @@
"SurfaceFlinger_GetDisplayNativePrimariesTest.cpp",
"SurfaceFlinger_HdrOutputControlTest.cpp",
"SurfaceFlinger_HotplugTest.cpp",
+ "SurfaceFlinger_InitializeDisplaysTest.cpp",
"SurfaceFlinger_MultiDisplayPacesetterTest.cpp",
"SurfaceFlinger_NotifyPowerBoostTest.cpp",
- "SurfaceFlinger_OnInitializeDisplaysTest.cpp",
"SurfaceFlinger_PowerHintTest.cpp",
"SurfaceFlinger_SetDisplayStateTest.cpp",
"SurfaceFlinger_SetPowerModeInternalTest.cpp",
diff --git a/services/surfaceflinger/tests/unittests/LayerHierarchyTest.cpp b/services/surfaceflinger/tests/unittests/LayerHierarchyTest.cpp
index 77dc868..ddf3363 100644
--- a/services/surfaceflinger/tests/unittests/LayerHierarchyTest.cpp
+++ b/services/surfaceflinger/tests/unittests/LayerHierarchyTest.cpp
@@ -17,12 +17,9 @@
#include <gmock/gmock.h>
#include <gtest/gtest.h>
-#include "FrontEnd/LayerHandle.h"
#include "FrontEnd/LayerHierarchy.h"
#include "FrontEnd/LayerLifecycleManager.h"
-#include "Layer.h"
#include "LayerHierarchyTest.h"
-#include "gui/SurfaceComposerClient.h"
#define UPDATE_AND_VERIFY(HIERARCHY) \
({ \
@@ -207,7 +204,8 @@
reparentRelativeLayer(11, 2);
UPDATE_AND_VERIFY(hierarchyBuilder);
- reparentRelativeLayer(11, UNASSIGNED_LAYER_ID);
+ // This calls setLayer
+ removeRelativeZ(11);
UPDATE_AND_VERIFY(hierarchyBuilder);
std::vector<uint32_t> expectedTraversalPath = {1, 11, 111, 12, 121, 122, 1221, 13, 2};
@@ -418,7 +416,7 @@
EXPECT_EQ(getTraversalPath(hierarchyBuilder.getOffscreenHierarchy()), expectedTraversalPath);
// remove relative parent so layer becomes onscreen again
- reparentRelativeLayer(11, UNASSIGNED_LAYER_ID);
+ removeRelativeZ(11);
UPDATE_AND_VERIFY(hierarchyBuilder);
expectedTraversalPath = {1, 11, 111, 12, 121, 122, 1221, 13};
diff --git a/services/surfaceflinger/tests/unittests/LayerHierarchyTest.h b/services/surfaceflinger/tests/unittests/LayerHierarchyTest.h
index b9a6159..5b3c7ef 100644
--- a/services/surfaceflinger/tests/unittests/LayerHierarchyTest.h
+++ b/services/surfaceflinger/tests/unittests/LayerHierarchyTest.h
@@ -17,11 +17,10 @@
#include <gmock/gmock.h>
#include <gtest/gtest.h>
-#include "FrontEnd/LayerHandle.h"
+#include "Client.h" // temporarily needed for LayerCreationArgs
+#include "FrontEnd/LayerCreationArgs.h"
#include "FrontEnd/LayerHierarchy.h"
#include "FrontEnd/LayerLifecycleManager.h"
-#include "Layer.h"
-#include "gui/SurfaceComposerClient.h"
namespace android::surfaceflinger::frontend {
@@ -51,20 +50,21 @@
createLayer(1221, 122);
}
- LayerCreationArgs createArgs(uint32_t id, bool canBeRoot, wp<IBinder> parent,
- wp<IBinder> mirror) {
- LayerCreationArgs args(nullptr, nullptr, "testlayer", 0, {}, std::make_optional(id));
+ LayerCreationArgs createArgs(uint32_t id, bool canBeRoot, uint32_t parentId,
+ uint32_t layerIdToMirror) {
+ LayerCreationArgs args(std::make_optional(id));
+ args.name = "testlayer";
args.addToRoot = canBeRoot;
- args.parentHandle = parent;
- args.mirrorLayerHandle = mirror;
+ args.parentId = parentId;
+ args.layerIdToMirror = layerIdToMirror;
return args;
}
- LayerCreationArgs createDisplayMirrorArgs(uint32_t id, ui::LayerStack layerStack) {
- LayerCreationArgs args(nullptr, nullptr, "testlayer", 0, {}, std::make_optional(id));
+ LayerCreationArgs createDisplayMirrorArgs(uint32_t id, ui::LayerStack layerStackToMirror) {
+ LayerCreationArgs args(std::make_optional(id));
+ args.name = "testlayer";
args.addToRoot = true;
- args.parentHandle.clear();
- args.layerStackToMirror = layerStack;
+ args.layerStackToMirror = layerStackToMirror;
return args;
}
@@ -90,17 +90,14 @@
}
virtual void createRootLayer(uint32_t id) {
- sp<LayerHandle> handle = sp<LayerHandle>::make(id);
- mHandles[id] = handle;
std::vector<std::unique_ptr<RequestedLayerState>> layers;
layers.emplace_back(std::make_unique<RequestedLayerState>(
- createArgs(/*id=*/id, /*canBeRoot=*/true, /*parent=*/nullptr, /*mirror=*/nullptr)));
+ createArgs(/*id=*/id, /*canBeRoot=*/true, /*parent=*/UNASSIGNED_LAYER_ID,
+ /*mirror=*/UNASSIGNED_LAYER_ID)));
mLifecycleManager.addLayers(std::move(layers));
}
void createDisplayMirrorLayer(uint32_t id, ui::LayerStack layerStack) {
- sp<LayerHandle> handle = sp<LayerHandle>::make(id);
- mHandles[id] = handle;
std::vector<std::unique_ptr<RequestedLayerState>> layers;
layers.emplace_back(std::make_unique<RequestedLayerState>(
createDisplayMirrorArgs(/*id=*/id, layerStack)));
@@ -108,62 +105,56 @@
}
virtual void createLayer(uint32_t id, uint32_t parentId) {
- sp<LayerHandle> handle = sp<LayerHandle>::make(id);
- mHandles[id] = handle;
std::vector<std::unique_ptr<RequestedLayerState>> layers;
layers.emplace_back(std::make_unique<RequestedLayerState>(
- createArgs(/*id=*/id, /*canBeRoot=*/false, /*parent=*/mHandles[parentId],
- /*mirror=*/nullptr)));
+ createArgs(/*id=*/id, /*canBeRoot=*/false, /*parent=*/parentId,
+ /*mirror=*/UNASSIGNED_LAYER_ID)));
mLifecycleManager.addLayers(std::move(layers));
}
- void reparentLayer(uint32_t id, uint32_t newParentId) {
+ std::vector<TransactionState> reparentLayerTransaction(uint32_t id, uint32_t newParentId) {
std::vector<TransactionState> transactions;
transactions.emplace_back();
transactions.back().states.push_back({});
-
- if (newParentId == UNASSIGNED_LAYER_ID) {
- transactions.back().states.front().state.parentSurfaceControlForChild = nullptr;
- } else {
- auto parentHandle = mHandles[newParentId];
- transactions.back().states.front().state.parentSurfaceControlForChild =
- sp<SurfaceControl>::make(SurfaceComposerClient::getDefault(), parentHandle,
- static_cast<int32_t>(newParentId), "Test");
- }
+ transactions.back().states.front().parentId = newParentId;
transactions.back().states.front().state.what = layer_state_t::eReparent;
- transactions.back().states.front().state.surface = mHandles[id];
- mLifecycleManager.applyTransactions(transactions);
+ transactions.back().states.front().relativeParentId = UNASSIGNED_LAYER_ID;
+ transactions.back().states.front().layerId = id;
+ return transactions;
+ }
+
+ void reparentLayer(uint32_t id, uint32_t newParentId) {
+ mLifecycleManager.applyTransactions(reparentLayerTransaction(id, newParentId));
+ }
+
+ std::vector<TransactionState> relativeLayerTransaction(uint32_t id, uint32_t relativeParentId) {
+ std::vector<TransactionState> transactions;
+ transactions.emplace_back();
+ transactions.back().states.push_back({});
+ transactions.back().states.front().relativeParentId = relativeParentId;
+ transactions.back().states.front().state.what = layer_state_t::eRelativeLayerChanged;
+ transactions.back().states.front().layerId = id;
+ return transactions;
}
void reparentRelativeLayer(uint32_t id, uint32_t relativeParentId) {
+ mLifecycleManager.applyTransactions(relativeLayerTransaction(id, relativeParentId));
+ }
+
+ void removeRelativeZ(uint32_t id) {
std::vector<TransactionState> transactions;
transactions.emplace_back();
transactions.back().states.push_back({});
-
- if (relativeParentId == UNASSIGNED_LAYER_ID) {
- transactions.back().states.front().state.what = layer_state_t::eLayerChanged;
- } else {
- auto parentHandle = mHandles[relativeParentId];
- transactions.back().states.front().state.relativeLayerSurfaceControl =
- sp<SurfaceControl>::make(SurfaceComposerClient::getDefault(), parentHandle,
- static_cast<int32_t>(relativeParentId), "test");
- transactions.back().states.front().state.what = layer_state_t::eRelativeLayerChanged;
- }
- transactions.back().states.front().state.surface = mHandles[id];
+ transactions.back().states.front().state.what = layer_state_t::eLayerChanged;
+ transactions.back().states.front().layerId = id;
mLifecycleManager.applyTransactions(transactions);
}
- virtual void mirrorLayer(uint32_t id, uint32_t parent, uint32_t layerToMirror) {
- auto parentHandle = (parent == UNASSIGNED_LAYER_ID) ? nullptr : mHandles[parent];
- auto mirrorHandle =
- (layerToMirror == UNASSIGNED_LAYER_ID) ? nullptr : mHandles[layerToMirror];
-
- sp<LayerHandle> handle = sp<LayerHandle>::make(id);
- mHandles[id] = handle;
+ virtual void mirrorLayer(uint32_t id, uint32_t parentId, uint32_t layerIdToMirror) {
std::vector<std::unique_ptr<RequestedLayerState>> layers;
layers.emplace_back(std::make_unique<RequestedLayerState>(
- createArgs(/*id=*/id, /*canBeRoot=*/false, /*parent=*/parentHandle,
- /*mirror=*/mHandles[layerToMirror])));
+ createArgs(/*id=*/id, /*canBeRoot=*/false, /*parent=*/parentId,
+ /*mirror=*/layerIdToMirror)));
mLifecycleManager.addLayers(std::move(layers));
}
@@ -173,7 +164,7 @@
transactions.back().states.push_back({});
transactions.back().states.front().state.what = layer_state_t::eBackgroundColorChanged;
transactions.back().states.front().state.bgColor.a = alpha;
- transactions.back().states.front().state.surface = mHandles[id];
+ transactions.back().states.front().layerId = id;
mLifecycleManager.applyTransactions(transactions);
}
@@ -196,16 +187,19 @@
mLifecycleManager.getGlobalChanges().test(RequestedLayerState::Changes::Hierarchy));
}
- void setZ(uint32_t id, int32_t z) {
+ std::vector<TransactionState> setZTransaction(uint32_t id, int32_t z) {
std::vector<TransactionState> transactions;
transactions.emplace_back();
transactions.back().states.push_back({});
transactions.back().states.front().state.what = layer_state_t::eLayerChanged;
- transactions.back().states.front().state.surface = mHandles[id];
- transactions.back().states.front().state.layerId = static_cast<int32_t>(id);
+ transactions.back().states.front().layerId = id;
transactions.back().states.front().state.z = z;
- mLifecycleManager.applyTransactions(transactions);
+ return transactions;
+ }
+
+ void setZ(uint32_t id, int32_t z) {
+ mLifecycleManager.applyTransactions(setZTransaction(id, z));
}
void setCrop(uint32_t id, const Rect& crop) {
@@ -214,8 +208,7 @@
transactions.back().states.push_back({});
transactions.back().states.front().state.what = layer_state_t::eCropChanged;
- transactions.back().states.front().state.surface = mHandles[id];
- transactions.back().states.front().state.layerId = static_cast<int32_t>(id);
+ transactions.back().states.front().layerId = id;
transactions.back().states.front().state.crop = crop;
mLifecycleManager.applyTransactions(transactions);
}
@@ -228,8 +221,7 @@
transactions.back().states.front().state.what = layer_state_t::eFlagsChanged;
transactions.back().states.front().state.flags = flags;
transactions.back().states.front().state.mask = mask;
- transactions.back().states.front().state.surface = mHandles[id];
- transactions.back().states.front().state.layerId = static_cast<int32_t>(id);
+ transactions.back().states.front().layerId = id;
mLifecycleManager.applyTransactions(transactions);
}
@@ -239,8 +231,7 @@
transactions.back().states.push_back({});
transactions.back().states.front().state.what = layer_state_t::eAlphaChanged;
- transactions.back().states.front().state.surface = mHandles[id];
- transactions.back().states.front().state.layerId = static_cast<int32_t>(id);
+ transactions.back().states.front().layerId = id;
transactions.back().states.front().state.color.a = static_cast<half>(alpha);
mLifecycleManager.applyTransactions(transactions);
}
@@ -257,8 +248,7 @@
transactions.back().states.push_back({});
transactions.back().states.front().state.what = layer_state_t::eColorChanged;
transactions.back().states.front().state.color.rgb = rgb;
- transactions.back().states.front().state.surface = mHandles[id];
- transactions.back().states.front().state.layerId = static_cast<int32_t>(id);
+ transactions.back().states.front().layerId = id;
mLifecycleManager.applyTransactions(transactions);
}
@@ -268,8 +258,7 @@
transactions.back().states.push_back({});
transactions.back().states.front().state.what = layer_state_t::eLayerStackChanged;
- transactions.back().states.front().state.surface = mHandles[id];
- transactions.back().states.front().state.layerId = static_cast<int32_t>(id);
+ transactions.back().states.front().layerId = id;
transactions.back().states.front().state.layerStack = ui::LayerStack::fromValue(layerStack);
mLifecycleManager.applyTransactions(transactions);
}
@@ -280,8 +269,7 @@
transactions.back().states.push_back({});
transactions.back().states.front().state.what = layer_state_t::eInputInfoChanged;
- transactions.back().states.front().state.surface = mHandles[id];
- transactions.back().states.front().state.layerId = static_cast<int32_t>(id);
+ transactions.back().states.front().layerId = id;
transactions.back().states.front().state.windowInfoHandle =
sp<gui::WindowInfoHandle>::make();
auto inputInfo = transactions.back().states.front().state.windowInfoHandle->editInfo();
@@ -291,7 +279,6 @@
}
LayerLifecycleManager mLifecycleManager;
- std::unordered_map<uint32_t, sp<LayerHandle>> mHandles;
};
} // namespace android::surfaceflinger::frontend
diff --git a/services/surfaceflinger/tests/unittests/LayerLifecycleManagerTest.cpp b/services/surfaceflinger/tests/unittests/LayerLifecycleManagerTest.cpp
index 99c1d23..14b8e4b 100644
--- a/services/surfaceflinger/tests/unittests/LayerLifecycleManagerTest.cpp
+++ b/services/surfaceflinger/tests/unittests/LayerLifecycleManagerTest.cpp
@@ -17,25 +17,14 @@
#include <gmock/gmock.h>
#include <gtest/gtest.h>
-#include "FrontEnd/LayerHandle.h"
#include "FrontEnd/LayerLifecycleManager.h"
-#include "Layer.h"
-#include "gui/SurfaceComposerClient.h"
+#include "LayerHierarchyTest.h"
+#include "TransactionState.h"
using namespace android::surfaceflinger;
namespace android::surfaceflinger::frontend {
-namespace {
-LayerCreationArgs createArgs(uint32_t id, bool canBeRoot, wp<IBinder> parent, wp<IBinder> mirror) {
- LayerCreationArgs args(nullptr, nullptr, "testlayer", 0, {}, std::make_optional(id));
- args.addToRoot = canBeRoot;
- args.parentHandle = parent;
- args.mirrorLayerHandle = mirror;
- return args;
-}
-} // namespace
-
// To run test:
/**
mp :libsurfaceflinger_unittest && adb sync; adb shell \
@@ -66,69 +55,24 @@
std::unordered_set<uint32_t> mActualLayersDestroyed;
};
-class LayerLifecycleManagerTest : public testing::Test {
+class LayerLifecycleManagerTest : public LayerHierarchyTestBase {
protected:
std::unique_ptr<RequestedLayerState> rootLayer(uint32_t id) {
- return std::make_unique<RequestedLayerState>(
- createArgs(/*id=*/id, /*canBeRoot=*/true, /*parent=*/nullptr, /*mirror=*/nullptr));
+ return std::make_unique<RequestedLayerState>(createArgs(/*id=*/id, /*canBeRoot=*/true,
+ /*parent=*/UNASSIGNED_LAYER_ID,
+ /*mirror=*/UNASSIGNED_LAYER_ID));
}
std::unique_ptr<RequestedLayerState> childLayer(uint32_t id, uint32_t parentId) {
- mHandles[parentId] = sp<LayerHandle>::make(parentId);
return std::make_unique<RequestedLayerState>(createArgs(/*id=*/id, /*canBeRoot=*/false,
- /*parent=*/mHandles[parentId],
- /*mirror=*/nullptr));
- }
-
- TransactionState reparentLayer(uint32_t id, uint32_t newParentId) {
- TransactionState transaction;
- transaction.states.push_back({});
-
- if (newParentId == UNASSIGNED_LAYER_ID) {
- transaction.states.front().state.parentSurfaceControlForChild = nullptr;
- } else {
- transaction.states.front().state.parentSurfaceControlForChild =
- sp<SurfaceControl>::make(SurfaceComposerClient::getDefault(),
- sp<LayerHandle>::make(newParentId),
- static_cast<int32_t>(newParentId), "Test");
- }
- transaction.states.front().state.what = layer_state_t::eReparent;
- transaction.states.front().state.surface = sp<LayerHandle>::make(id);
- return transaction;
- }
-
- TransactionState setLayer(uint32_t id, int32_t z) {
- TransactionState transaction;
- transaction.states.push_back({});
- transaction.states.front().state.z = z;
- transaction.states.front().state.what = layer_state_t::eLayerChanged;
- transaction.states.front().state.surface = sp<LayerHandle>::make(id);
- return transaction;
- }
-
- TransactionState makeRelative(uint32_t id, uint32_t relativeParentId) {
- TransactionState transaction;
- transaction.states.push_back({});
-
- if (relativeParentId == UNASSIGNED_LAYER_ID) {
- transaction.states.front().state.relativeLayerSurfaceControl = nullptr;
- } else {
- transaction.states.front().state.relativeLayerSurfaceControl =
- sp<SurfaceControl>::make(SurfaceComposerClient::getDefault(),
- sp<LayerHandle>::make(relativeParentId),
- static_cast<int32_t>(relativeParentId), "Test");
- }
- transaction.states.front().state.what = layer_state_t::eRelativeLayerChanged;
- transaction.states.front().state.surface = sp<LayerHandle>::make(id);
- return transaction;
+ parentId,
+ /*mirror=*/UNASSIGNED_LAYER_ID));
}
RequestedLayerState* getRequestedLayerState(LayerLifecycleManager& lifecycleManager,
uint32_t layerId) {
return lifecycleManager.getLayerFromId(layerId);
}
-
- std::unordered_map<uint32_t, sp<LayerHandle>> mHandles;
};
TEST_F(LayerLifecycleManagerTest, addLayers) {
@@ -153,16 +97,7 @@
std::vector<std::unique_ptr<RequestedLayerState>> layers;
layers.emplace_back(rootLayer(1));
lifecycleManager.addLayers(std::move(layers));
-
- std::vector<TransactionState> transactions;
- transactions.emplace_back();
- transactions.back().states.push_back({});
- transactions.back().states.front().state.z = 2;
- transactions.back().states.front().state.what = layer_state_t::eLayerChanged;
- sp<LayerHandle> handle = sp<LayerHandle>::make(1u);
- transactions.back().states.front().state.surface = handle;
- lifecycleManager.applyTransactions(transactions);
- transactions.clear();
+ lifecycleManager.applyTransactions(setZTransaction(1, 2));
auto& managedLayers = lifecycleManager.getLayers();
ASSERT_EQ(managedLayers.size(), 1u);
@@ -177,11 +112,12 @@
EXPECT_FALSE(managedLayers.front()->changes.test(RequestedLayerState::Changes::Z));
// apply transactions that do not affect the hierarchy
+ std::vector<TransactionState> transactions;
transactions.emplace_back();
transactions.back().states.push_back({});
transactions.back().states.front().state.backgroundBlurRadius = 22;
transactions.back().states.front().state.what = layer_state_t::eBackgroundBlurRadiusChanged;
- transactions.back().states.front().state.surface = handle;
+ transactions.back().states.front().layerId = 1;
lifecycleManager.applyTransactions(transactions);
EXPECT_FALSE(lifecycleManager.getGlobalChanges().test(RequestedLayerState::Changes::Hierarchy));
lifecycleManager.commitChanges();
@@ -232,7 +168,7 @@
listener->expectLayersAdded({1, 2, 3});
listener->expectLayersDestroyed({});
- lifecycleManager.applyTransactions({reparentLayer(3, UNASSIGNED_LAYER_ID)});
+ lifecycleManager.applyTransactions(reparentLayerTransaction(3, UNASSIGNED_LAYER_ID));
lifecycleManager.commitChanges();
listener->expectLayersAdded({});
listener->expectLayersDestroyed({});
@@ -257,7 +193,7 @@
listener->expectLayersAdded({1, 2, 3, 4});
listener->expectLayersDestroyed({});
- lifecycleManager.applyTransactions({reparentLayer(3, UNASSIGNED_LAYER_ID)});
+ lifecycleManager.applyTransactions(reparentLayerTransaction(3, UNASSIGNED_LAYER_ID));
lifecycleManager.onHandlesDestroyed({3});
lifecycleManager.commitChanges();
listener->expectLayersAdded({});
@@ -278,7 +214,7 @@
listener->expectLayersAdded({1, 2, 3, 4});
listener->expectLayersDestroyed({});
- lifecycleManager.applyTransactions({reparentLayer(3, UNASSIGNED_LAYER_ID)});
+ lifecycleManager.applyTransactions(reparentLayerTransaction(3, UNASSIGNED_LAYER_ID));
lifecycleManager.onHandlesDestroyed({3, 4});
lifecycleManager.commitChanges();
listener->expectLayersAdded({});
@@ -300,9 +236,9 @@
listener->expectLayersAdded({1, 2, 3, 4});
listener->expectLayersDestroyed({});
- lifecycleManager.applyTransactions({makeRelative(4, 1)});
+ lifecycleManager.applyTransactions(relativeLayerTransaction(4, 1));
EXPECT_TRUE(getRequestedLayerState(lifecycleManager, 4)->isRelativeOf);
- lifecycleManager.applyTransactions({reparentLayer(4, 2)});
+ lifecycleManager.applyTransactions(reparentLayerTransaction(4, 2));
EXPECT_TRUE(getRequestedLayerState(lifecycleManager, 4)->isRelativeOf);
lifecycleManager.commitChanges();
@@ -325,9 +261,9 @@
listener->expectLayersAdded({1, 2, 3, 4});
listener->expectLayersDestroyed({});
- lifecycleManager.applyTransactions({makeRelative(4, 1)});
+ lifecycleManager.applyTransactions(relativeLayerTransaction(4, 1));
EXPECT_TRUE(getRequestedLayerState(lifecycleManager, 4)->isRelativeOf);
- lifecycleManager.applyTransactions({reparentLayer(4, UNASSIGNED_LAYER_ID)});
+ lifecycleManager.applyTransactions(reparentLayerTransaction(4, UNASSIGNED_LAYER_ID));
EXPECT_FALSE(getRequestedLayerState(lifecycleManager, 4)->isRelativeOf);
lifecycleManager.commitChanges();
@@ -350,9 +286,9 @@
listener->expectLayersAdded({1, 2, 3, 4});
listener->expectLayersDestroyed({});
- lifecycleManager.applyTransactions({makeRelative(4, 1)});
+ lifecycleManager.applyTransactions(relativeLayerTransaction(4, 1));
EXPECT_TRUE(getRequestedLayerState(lifecycleManager, 4)->isRelativeOf);
- lifecycleManager.applyTransactions({setLayer(4, 1)});
+ lifecycleManager.applyTransactions(setZTransaction(4, 1));
EXPECT_FALSE(getRequestedLayerState(lifecycleManager, 4)->isRelativeOf);
lifecycleManager.commitChanges();
@@ -374,8 +310,7 @@
transactions.back().states.push_back({});
transactions.back().states.front().state.bgColor.a = 0.5;
transactions.back().states.front().state.what = layer_state_t::eBackgroundColorChanged;
- sp<LayerHandle> handle = sp<LayerHandle>::make(1u);
- transactions.back().states.front().state.surface = handle;
+ transactions.back().states.front().layerId = 1;
lifecycleManager.applyTransactions(transactions);
auto& managedLayers = lifecycleManager.getLayers();
@@ -403,13 +338,12 @@
transactions.back().states.push_back({});
transactions.back().states.front().state.bgColor.a = 0.5;
transactions.back().states.front().state.what = layer_state_t::eBackgroundColorChanged;
- sp<LayerHandle> handle = sp<LayerHandle>::make(1u);
- transactions.back().states.front().state.surface = handle;
+ transactions.back().states.front().layerId = 1;
transactions.emplace_back();
transactions.back().states.push_back({});
transactions.back().states.front().state.bgColor.a = 0;
transactions.back().states.front().state.what = layer_state_t::eBackgroundColorChanged;
- transactions.back().states.front().state.surface = handle;
+ transactions.back().states.front().layerId = 1;
lifecycleManager.applyTransactions(transactions);
@@ -437,8 +371,7 @@
transactions.back().states.push_back({});
transactions.back().states.front().state.bgColor.a = 0.5;
transactions.back().states.front().state.what = layer_state_t::eBackgroundColorChanged;
- sp<LayerHandle> handle = sp<LayerHandle>::make(1u);
- transactions.back().states.front().state.surface = handle;
+ transactions.back().states.front().layerId = 1;
transactions.emplace_back();
lifecycleManager.applyTransactions(transactions);
lifecycleManager.onHandlesDestroyed({1});
diff --git a/services/surfaceflinger/tests/unittests/LayerSnapshotTest.cpp b/services/surfaceflinger/tests/unittests/LayerSnapshotTest.cpp
index db0b907..b8c4781 100644
--- a/services/surfaceflinger/tests/unittests/LayerSnapshotTest.cpp
+++ b/services/surfaceflinger/tests/unittests/LayerSnapshotTest.cpp
@@ -17,11 +17,9 @@
#include <gmock/gmock.h>
#include <gtest/gtest.h>
-#include "FrontEnd/LayerHandle.h"
#include "FrontEnd/LayerHierarchy.h"
#include "FrontEnd/LayerLifecycleManager.h"
#include "FrontEnd/LayerSnapshotBuilder.h"
-#include "Layer.h"
#include "LayerHierarchyTest.h"
#define UPDATE_AND_VERIFY(BUILDER, ...) \
@@ -268,7 +266,7 @@
transactions.back().states.front().state.what = layer_state_t::eMetadataChanged;
transactions.back().states.front().state.metadata = LayerMetadata();
transactions.back().states.front().state.metadata.setInt32(METADATA_GAME_MODE, 42);
- transactions.back().states.front().state.surface = mHandles[1];
+ transactions.back().states.front().layerId = 1;
transactions.back().states.front().state.layerId = static_cast<int32_t>(1);
mLifecycleManager.applyTransactions(transactions);
UPDATE_AND_VERIFY(mSnapshotBuilder, STARTING_ZORDER);
@@ -297,8 +295,7 @@
ANATIVEWINDOW_FRAME_RATE_EXACT;
transactions.back().states.front().state.changeFrameRateStrategy =
ANATIVEWINDOW_CHANGE_FRAME_RATE_ALWAYS;
- transactions.back().states.front().state.surface = mHandles[11];
- transactions.back().states.front().state.layerId = static_cast<int32_t>(11);
+ transactions.back().states.front().layerId = 11;
mLifecycleManager.applyTransactions(transactions);
UPDATE_AND_VERIFY(mSnapshotBuilder, STARTING_ZORDER);
diff --git a/services/surfaceflinger/tests/unittests/SurfaceFlinger_DisplayModeSwitching.cpp b/services/surfaceflinger/tests/unittests/SurfaceFlinger_DisplayModeSwitching.cpp
index fd1fd47..e176546 100644
--- a/services/surfaceflinger/tests/unittests/SurfaceFlinger_DisplayModeSwitching.cpp
+++ b/services/surfaceflinger/tests/unittests/SurfaceFlinger_DisplayModeSwitching.cpp
@@ -119,7 +119,7 @@
ASSERT_FALSE(mDisplay->getDesiredActiveMode().has_value());
ASSERT_EQ(mDisplay->getActiveMode().modePtr->getId(), kModeId60);
- mFlinger.onActiveDisplayChanged(*mDisplay);
+ mFlinger.onActiveDisplayChanged(nullptr, *mDisplay);
mFlinger.setDesiredDisplayModeSpecs(mDisplay->getDisplayToken().promote(),
mock::createDisplayModeSpecs(kModeId90.value(), false, 0,
@@ -159,7 +159,7 @@
ASSERT_FALSE(mDisplay->getDesiredActiveMode().has_value());
- mFlinger.onActiveDisplayChanged(*mDisplay);
+ mFlinger.onActiveDisplayChanged(nullptr, *mDisplay);
mFlinger.setDesiredDisplayModeSpecs(mDisplay->getDisplayToken().promote(),
mock::createDisplayModeSpecs(kModeId90.value(), true, 0,
@@ -195,7 +195,7 @@
ASSERT_FALSE(mDisplay->getDesiredActiveMode().has_value());
ASSERT_EQ(mDisplay->getActiveMode().modePtr->getId(), kModeId60);
- mFlinger.onActiveDisplayChanged(*mDisplay);
+ mFlinger.onActiveDisplayChanged(nullptr, *mDisplay);
mFlinger.setDesiredDisplayModeSpecs(mDisplay->getDisplayToken().promote(),
mock::createDisplayModeSpecs(kModeId90.value(), false, 0,
@@ -238,7 +238,7 @@
ASSERT_FALSE(mDisplay->getDesiredActiveMode().has_value());
ASSERT_EQ(mDisplay->getActiveMode().modePtr->getId(), kModeId60);
- mFlinger.onActiveDisplayChanged(*mDisplay);
+ mFlinger.onActiveDisplayChanged(nullptr, *mDisplay);
mFlinger.setDesiredDisplayModeSpecs(mDisplay->getDisplayToken().promote(),
mock::createDisplayModeSpecs(kModeId90_4K.value(), false, 0,
@@ -284,9 +284,43 @@
ASSERT_EQ(mDisplay->getActiveMode().modePtr->getId(), kModeId90_4K);
}
-TEST_F(DisplayModeSwitchingTest, multiDisplay) {
+MATCHER_P2(ModeSwitchingTo, flinger, modeId, "") {
+ if (!arg->getDesiredActiveMode()) {
+ *result_listener << "No desired active mode";
+ return false;
+ }
+
+ if (arg->getDesiredActiveMode()->modeOpt->modePtr->getId() != modeId) {
+ *result_listener << "Unexpected desired active mode " << modeId;
+ return false;
+ }
+
+ if (!flinger->scheduler()->vsyncModulator().isVsyncConfigEarly()) {
+ *result_listener << "VsyncModulator did not shift to early phase";
+ return false;
+ }
+
+ return true;
+}
+
+MATCHER_P(ModeSettledTo, modeId, "") {
+ if (const auto desiredOpt = arg->getDesiredActiveMode()) {
+ *result_listener << "Unsettled desired active mode "
+ << desiredOpt->modeOpt->modePtr->getId();
+ return false;
+ }
+
ftl::FakeGuard guard(kMainThreadContext);
+ if (arg->getActiveMode().modePtr->getId() != modeId) {
+ *result_listener << "Settled to unexpected active mode " << modeId;
+ return false;
+ }
+
+ return true;
+}
+
+TEST_F(DisplayModeSwitchingTest, multiDisplay) {
constexpr HWDisplayId kInnerDisplayHwcId = PrimaryDisplayVariant::HWC_DISPLAY_ID;
constexpr HWDisplayId kOuterDisplayHwcId = kInnerDisplayHwcId + 1;
@@ -309,13 +343,13 @@
const auto& innerDisplay = mDisplay;
- EXPECT_FALSE(innerDisplay->getDesiredActiveMode());
- EXPECT_FALSE(outerDisplay->getDesiredActiveMode());
+ EXPECT_THAT(innerDisplay, ModeSettledTo(kModeId60));
+ EXPECT_THAT(outerDisplay, ModeSettledTo(kModeId120));
- EXPECT_EQ(innerDisplay->getActiveMode().modePtr->getId(), kModeId60);
- EXPECT_EQ(outerDisplay->getActiveMode().modePtr->getId(), kModeId120);
+ mFlinger.onActiveDisplayChanged(nullptr, *innerDisplay);
- mFlinger.onActiveDisplayChanged(*innerDisplay);
+ EXPECT_THAT(innerDisplay, ModeSettledTo(kModeId60));
+ EXPECT_THAT(outerDisplay, ModeSettledTo(kModeId120));
EXPECT_EQ(NO_ERROR,
mFlinger.setDesiredDisplayModeSpecs(innerDisplay->getDisplayToken().promote(),
@@ -327,12 +361,8 @@
mock::createDisplayModeSpecs(kModeId60.value(),
false, 0.f, 120.f)));
- // Transition on the inner display.
- ASSERT_TRUE(innerDisplay->getDesiredActiveMode());
- EXPECT_EQ(innerDisplay->getDesiredActiveMode()->modeOpt->modePtr->getId(), kModeId90);
-
- // No transition on the outer display.
- EXPECT_FALSE(outerDisplay->getDesiredActiveMode());
+ EXPECT_THAT(innerDisplay, ModeSwitchingTo(&mFlinger, kModeId90));
+ EXPECT_THAT(outerDisplay, ModeSettledTo(kModeId120));
const VsyncPeriodChangeTimeline timeline{.refreshRequired = true};
EXPECT_CALL(*mComposer,
@@ -342,31 +372,18 @@
mFlinger.commit();
- // Transition on the inner display.
- ASSERT_TRUE(innerDisplay->getDesiredActiveMode());
- EXPECT_EQ(innerDisplay->getDesiredActiveMode()->modeOpt->modePtr->getId(), kModeId90);
-
- // No transition on the outer display.
- EXPECT_FALSE(outerDisplay->getDesiredActiveMode());
+ EXPECT_THAT(innerDisplay, ModeSwitchingTo(&mFlinger, kModeId90));
+ EXPECT_THAT(outerDisplay, ModeSettledTo(kModeId120));
mFlinger.commit();
- // Transition on the inner display.
- EXPECT_FALSE(innerDisplay->getDesiredActiveMode());
- EXPECT_EQ(innerDisplay->getActiveMode().modePtr->getId(), kModeId90);
+ EXPECT_THAT(innerDisplay, ModeSettledTo(kModeId90));
+ EXPECT_THAT(outerDisplay, ModeSettledTo(kModeId120));
- // No transition on the outer display.
- EXPECT_FALSE(outerDisplay->getDesiredActiveMode());
- EXPECT_EQ(outerDisplay->getActiveMode().modePtr->getId(), kModeId120);
+ mFlinger.onActiveDisplayChanged(innerDisplay.get(), *outerDisplay);
- mFlinger.onActiveDisplayChanged(*outerDisplay);
-
- // No transition on the inner display.
- EXPECT_FALSE(innerDisplay->getDesiredActiveMode());
-
- // Transition on the outer display.
- ASSERT_TRUE(outerDisplay->getDesiredActiveMode());
- EXPECT_EQ(outerDisplay->getDesiredActiveMode()->modeOpt->modePtr->getId(), kModeId60);
+ EXPECT_THAT(innerDisplay, ModeSettledTo(kModeId90));
+ EXPECT_THAT(outerDisplay, ModeSwitchingTo(&mFlinger, kModeId60));
EXPECT_CALL(*mComposer,
setActiveConfigWithConstraints(kOuterDisplayHwcId,
@@ -375,22 +392,13 @@
mFlinger.commit();
- // No transition on the inner display.
- EXPECT_FALSE(innerDisplay->getDesiredActiveMode());
-
- // Transition on the outer display.
- ASSERT_TRUE(outerDisplay->getDesiredActiveMode());
- EXPECT_EQ(outerDisplay->getDesiredActiveMode()->modeOpt->modePtr->getId(), kModeId60);
+ EXPECT_THAT(innerDisplay, ModeSettledTo(kModeId90));
+ EXPECT_THAT(outerDisplay, ModeSwitchingTo(&mFlinger, kModeId60));
mFlinger.commit();
- // No transition on the inner display.
- EXPECT_FALSE(innerDisplay->getDesiredActiveMode());
- EXPECT_EQ(innerDisplay->getActiveMode().modePtr->getId(), kModeId90);
-
- // Transition on the outer display.
- EXPECT_FALSE(outerDisplay->getDesiredActiveMode());
- EXPECT_EQ(outerDisplay->getActiveMode().modePtr->getId(), kModeId60);
+ EXPECT_THAT(innerDisplay, ModeSettledTo(kModeId90));
+ EXPECT_THAT(outerDisplay, ModeSettledTo(kModeId60));
}
} // namespace
diff --git a/services/surfaceflinger/tests/unittests/SurfaceFlinger_OnInitializeDisplaysTest.cpp b/services/surfaceflinger/tests/unittests/SurfaceFlinger_InitializeDisplaysTest.cpp
similarity index 93%
rename from services/surfaceflinger/tests/unittests/SurfaceFlinger_OnInitializeDisplaysTest.cpp
rename to services/surfaceflinger/tests/unittests/SurfaceFlinger_InitializeDisplaysTest.cpp
index 98644aa..fc5f2b0 100644
--- a/services/surfaceflinger/tests/unittests/SurfaceFlinger_OnInitializeDisplaysTest.cpp
+++ b/services/surfaceflinger/tests/unittests/SurfaceFlinger_InitializeDisplaysTest.cpp
@@ -22,9 +22,9 @@
namespace android {
namespace {
-class OnInitializeDisplaysTest : public DisplayTransactionTest {};
+class InitializeDisplaysTest : public DisplayTransactionTest {};
-TEST_F(OnInitializeDisplaysTest, onInitializeDisplaysSetsUpPrimaryDisplay) {
+TEST_F(InitializeDisplaysTest, commitsPrimaryDisplay) {
using Case = SimplePrimaryDisplayCase;
// --------------------------------------------------------------------
@@ -52,7 +52,7 @@
// --------------------------------------------------------------------
// Invocation
- mFlinger.onInitializeDisplays();
+ FTL_FAKE_GUARD(kMainThreadContext, mFlinger.initializeDisplays());
// --------------------------------------------------------------------
// Postconditions
diff --git a/services/surfaceflinger/tests/unittests/TestableScheduler.h b/services/surfaceflinger/tests/unittests/TestableScheduler.h
index d4b4434..f1a5fc4 100644
--- a/services/surfaceflinger/tests/unittests/TestableScheduler.h
+++ b/services/surfaceflinger/tests/unittests/TestableScheduler.h
@@ -102,7 +102,6 @@
}
auto& mutableAppConnectionHandle() { return mAppConnectionHandle; }
- auto& mutableVsyncModulator() { return *mVsyncModulator; }
auto& mutableLayerHistory() { return mLayerHistory; }
size_t layerHistorySize() NO_THREAD_SAFETY_ANALYSIS {
diff --git a/services/surfaceflinger/tests/unittests/TestableSurfaceFlinger.h b/services/surfaceflinger/tests/unittests/TestableSurfaceFlinger.h
index 6334ec8..fc9e653 100644
--- a/services/surfaceflinger/tests/unittests/TestableSurfaceFlinger.h
+++ b/services/surfaceflinger/tests/unittests/TestableSurfaceFlinger.h
@@ -419,10 +419,7 @@
return mFlinger->setDisplayStateLocked(s);
}
- // Allow reading display state without locking, as if called on the SF main thread.
- auto onInitializeDisplays() NO_THREAD_SAFETY_ANALYSIS {
- return mFlinger->onInitializeDisplays();
- }
+ void initializeDisplays() FTL_FAKE_GUARD(kMainThreadContext) { mFlinger->initializeDisplays(); }
auto notifyPowerBoost(int32_t boostId) { return mFlinger->notifyPowerBoost(boostId); }
@@ -505,10 +502,11 @@
return mFlinger->setDesiredDisplayModeSpecs(displayToken, specs);
}
- void onActiveDisplayChanged(const DisplayDevice& activeDisplay) {
+ void onActiveDisplayChanged(const DisplayDevice* inactiveDisplayPtr,
+ const DisplayDevice& activeDisplay) {
Mutex::Autolock lock(mFlinger->mStateLock);
ftl::FakeGuard guard(kMainThreadContext);
- mFlinger->onActiveDisplayChangedLocked(nullptr, activeDisplay);
+ mFlinger->onActiveDisplayChangedLocked(inactiveDisplayPtr, activeDisplay);
}
auto createLayer(LayerCreationArgs& args, const sp<IBinder>& parentHandle,
diff --git a/services/surfaceflinger/tests/unittests/TransactionApplicationTest.cpp b/services/surfaceflinger/tests/unittests/TransactionApplicationTest.cpp
index c78148f..d4e2357 100644
--- a/services/surfaceflinger/tests/unittests/TransactionApplicationTest.cpp
+++ b/services/surfaceflinger/tests/unittests/TransactionApplicationTest.cpp
@@ -199,7 +199,7 @@
void modulateVsync() {
static_cast<void>(
- mFlinger.mutableScheduler().mutableVsyncModulator().onRefreshRateChangeInitiated());
+ mFlinger.mutableScheduler().vsyncModulator().onRefreshRateChangeInitiated());
}
bool mHasListenerCallbacks = false;