1 /*
2 * Copyright (C) 2018 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17 #undef LOG_TAG
18 #define LOG_TAG "DisplayIdentification"
19
20 #include <algorithm>
21 #include <cctype>
22 #include <numeric>
23 #include <optional>
24
25 #include <log/log.h>
26
27 #include <ui/DisplayIdentification.h>
28
29 namespace android {
30 namespace {
31
32 template <class T>
load(const void * p)33 inline T load(const void* p) {
34 static_assert(std::is_integral<T>::value, "T must be integral");
35
36 T r;
37 std::memcpy(&r, p, sizeof(r));
38 return r;
39 }
40
rotateByAtLeast1(uint64_t val,uint8_t shift)41 uint64_t rotateByAtLeast1(uint64_t val, uint8_t shift) {
42 return (val >> shift) | (val << (64 - shift));
43 }
44
shiftMix(uint64_t val)45 uint64_t shiftMix(uint64_t val) {
46 return val ^ (val >> 47);
47 }
48
hash64Len16(uint64_t u,uint64_t v)49 uint64_t hash64Len16(uint64_t u, uint64_t v) {
50 constexpr uint64_t kMul = 0x9ddfea08eb382d69;
51 uint64_t a = (u ^ v) * kMul;
52 a ^= (a >> 47);
53 uint64_t b = (v ^ a) * kMul;
54 b ^= (b >> 47);
55 b *= kMul;
56 return b;
57 }
58
hash64Len0To16(const char * s,uint64_t len)59 uint64_t hash64Len0To16(const char* s, uint64_t len) {
60 constexpr uint64_t k2 = 0x9ae16a3b2f90404f;
61 constexpr uint64_t k3 = 0xc949d7c7509e6557;
62
63 if (len > 8) {
64 const uint64_t a = load<uint64_t>(s);
65 const uint64_t b = load<uint64_t>(s + len - 8);
66 return hash64Len16(a, rotateByAtLeast1(b + len, static_cast<uint8_t>(len))) ^ b;
67 }
68 if (len >= 4) {
69 const uint32_t a = load<uint32_t>(s);
70 const uint32_t b = load<uint32_t>(s + len - 4);
71 return hash64Len16(len + (a << 3), b);
72 }
73 if (len > 0) {
74 const unsigned char a = static_cast<unsigned char>(s[0]);
75 const unsigned char b = static_cast<unsigned char>(s[len >> 1]);
76 const unsigned char c = static_cast<unsigned char>(s[len - 1]);
77 const uint32_t y = static_cast<uint32_t>(a) + (static_cast<uint32_t>(b) << 8);
78 const uint32_t z = static_cast<uint32_t>(len) + (static_cast<uint32_t>(c) << 2);
79 return shiftMix(y * k2 ^ z * k3) * k2;
80 }
81 return k2;
82 }
83
84 using byte_view = std::basic_string_view<uint8_t>;
85
86 constexpr size_t kEdidBlockSize = 128;
87 constexpr size_t kEdidHeaderLength = 5;
88
89 constexpr uint16_t kVirtualEdidManufacturerId = 0xffffu;
90
getEdidDescriptorType(const byte_view & view)91 std::optional<uint8_t> getEdidDescriptorType(const byte_view& view) {
92 if (view.size() < kEdidHeaderLength || view[0] || view[1] || view[2] || view[4]) {
93 return {};
94 }
95
96 return view[3];
97 }
98
parseEdidText(const byte_view & view)99 std::string_view parseEdidText(const byte_view& view) {
100 std::string_view text(reinterpret_cast<const char*>(view.data()), view.size());
101 text = text.substr(0, text.find('\n'));
102
103 if (!std::all_of(text.begin(), text.end(), ::isprint)) {
104 ALOGW("Invalid EDID: ASCII text is not printable.");
105 return {};
106 }
107
108 return text;
109 }
110
111 // Big-endian 16-bit value encodes three 5-bit letters where A is 0b00001.
112 template <size_t I>
getPnpLetter(uint16_t id)113 char getPnpLetter(uint16_t id) {
114 static_assert(I < 3);
115 const char letter = 'A' + (static_cast<uint8_t>(id >> ((2 - I) * 5)) & 0b00011111) - 1;
116 return letter < 'A' || letter > 'Z' ? '\0' : letter;
117 }
118
buildDeviceProductInfo(const Edid & edid)119 DeviceProductInfo buildDeviceProductInfo(const Edid& edid) {
120 DeviceProductInfo info;
121 info.name.assign(edid.displayName);
122 info.productId = std::to_string(edid.productId);
123 info.manufacturerPnpId = edid.pnpId;
124
125 constexpr uint8_t kModelYearFlag = 0xff;
126 constexpr uint32_t kYearOffset = 1990;
127
128 const auto year = edid.manufactureOrModelYear + kYearOffset;
129 if (edid.manufactureWeek == kModelYearFlag) {
130 info.manufactureOrModelDate = DeviceProductInfo::ModelYear{.year = year};
131 } else if (edid.manufactureWeek == 0) {
132 DeviceProductInfo::ManufactureYear date;
133 date.year = year;
134 info.manufactureOrModelDate = date;
135 } else {
136 DeviceProductInfo::ManufactureWeekAndYear date;
137 date.year = year;
138 date.week = edid.manufactureWeek;
139 info.manufactureOrModelDate = date;
140 }
141
142 if (edid.cea861Block && edid.cea861Block->hdmiVendorDataBlock) {
143 const auto& address = edid.cea861Block->hdmiVendorDataBlock->physicalAddress;
144 info.relativeAddress = {address.a, address.b, address.c, address.d};
145 }
146 return info;
147 }
148
parseCea861Block(const byte_view & block)149 Cea861ExtensionBlock parseCea861Block(const byte_view& block) {
150 Cea861ExtensionBlock cea861Block;
151
152 constexpr size_t kRevisionNumberOffset = 1;
153 cea861Block.revisionNumber = block[kRevisionNumberOffset];
154
155 constexpr size_t kDetailedTimingDescriptorsOffset = 2;
156 const size_t dtdStart =
157 std::min(kEdidBlockSize, static_cast<size_t>(block[kDetailedTimingDescriptorsOffset]));
158
159 // Parse data blocks.
160 for (size_t dataBlockOffset = 4; dataBlockOffset < dtdStart;) {
161 const uint8_t header = block[dataBlockOffset];
162 const uint8_t tag = header >> 5;
163 const size_t bodyLength = header & 0b11111;
164 constexpr size_t kDataBlockHeaderSize = 1;
165 const size_t dataBlockSize = bodyLength + kDataBlockHeaderSize;
166
167 if (block.size() < dataBlockOffset + dataBlockSize) {
168 ALOGW("Invalid EDID: CEA 861 data block is truncated.");
169 break;
170 }
171
172 const byte_view dataBlock(block.data() + dataBlockOffset, dataBlockSize);
173 constexpr uint8_t kVendorSpecificDataBlockTag = 0x3;
174
175 if (tag == kVendorSpecificDataBlockTag) {
176 const uint32_t ieeeRegistrationId = static_cast<uint32_t>(
177 dataBlock[1] | (dataBlock[2] << 8) | (dataBlock[3] << 16));
178 constexpr uint32_t kHdmiIeeeRegistrationId = 0xc03;
179
180 if (ieeeRegistrationId == kHdmiIeeeRegistrationId) {
181 const uint8_t a = dataBlock[4] >> 4;
182 const uint8_t b = dataBlock[4] & 0b1111;
183 const uint8_t c = dataBlock[5] >> 4;
184 const uint8_t d = dataBlock[5] & 0b1111;
185 cea861Block.hdmiVendorDataBlock =
186 HdmiVendorDataBlock{.physicalAddress = HdmiPhysicalAddress{a, b, c, d}};
187 } else {
188 ALOGV("Ignoring vendor specific data block for vendor with IEEE OUI %x",
189 ieeeRegistrationId);
190 }
191 } else {
192 ALOGV("Ignoring CEA-861 data block with tag %x", tag);
193 }
194 dataBlockOffset += bodyLength + kDataBlockHeaderSize;
195 }
196
197 return cea861Block;
198 }
199
200 } // namespace
201
isEdid(const DisplayIdentificationData & data)202 bool isEdid(const DisplayIdentificationData& data) {
203 const uint8_t kMagic[] = {0, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0};
204 return data.size() >= sizeof(kMagic) &&
205 std::equal(std::begin(kMagic), std::end(kMagic), data.begin());
206 }
207
parseEdid(const DisplayIdentificationData & edid)208 std::optional<Edid> parseEdid(const DisplayIdentificationData& edid) {
209 if (edid.size() < kEdidBlockSize) {
210 ALOGW("Invalid EDID: structure is truncated.");
211 // Attempt parsing even if EDID is malformed.
212 } else {
213 ALOGW_IF(std::accumulate(edid.begin(), edid.begin() + kEdidBlockSize,
214 static_cast<uint8_t>(0)),
215 "Invalid EDID: structure does not checksum.");
216 }
217
218 constexpr size_t kManufacturerOffset = 8;
219 if (edid.size() < kManufacturerOffset + sizeof(uint16_t)) {
220 ALOGE("Invalid EDID: manufacturer ID is truncated.");
221 return {};
222 }
223
224 // Plug and play ID encoded as big-endian 16-bit value.
225 const uint16_t manufacturerId =
226 static_cast<uint16_t>((edid[kManufacturerOffset] << 8) | edid[kManufacturerOffset + 1]);
227
228 const auto pnpId = getPnpId(manufacturerId);
229 if (!pnpId) {
230 ALOGE("Invalid EDID: manufacturer ID is not a valid PnP ID.");
231 return {};
232 }
233
234 constexpr size_t kProductIdOffset = 10;
235 if (edid.size() < kProductIdOffset + sizeof(uint16_t)) {
236 ALOGE("Invalid EDID: product ID is truncated.");
237 return {};
238 }
239 const uint16_t productId =
240 static_cast<uint16_t>(edid[kProductIdOffset] | (edid[kProductIdOffset + 1] << 8));
241
242 constexpr size_t kManufactureWeekOffset = 16;
243 if (edid.size() < kManufactureWeekOffset + sizeof(uint8_t)) {
244 ALOGE("Invalid EDID: manufacture week is truncated.");
245 return {};
246 }
247 const uint8_t manufactureWeek = edid[kManufactureWeekOffset];
248 ALOGW_IF(0x37 <= manufactureWeek && manufactureWeek <= 0xfe,
249 "Invalid EDID: week of manufacture cannot be in the range [0x37, 0xfe].");
250
251 constexpr size_t kManufactureYearOffset = 17;
252 if (edid.size() < kManufactureYearOffset + sizeof(uint8_t)) {
253 ALOGE("Invalid EDID: manufacture year is truncated.");
254 return {};
255 }
256 const uint8_t manufactureOrModelYear = edid[kManufactureYearOffset];
257 ALOGW_IF(manufactureOrModelYear <= 0xf,
258 "Invalid EDID: model year or manufacture year cannot be in the range [0x0, 0xf].");
259
260 constexpr size_t kDescriptorOffset = 54;
261 if (edid.size() < kDescriptorOffset) {
262 ALOGE("Invalid EDID: descriptors are missing.");
263 return {};
264 }
265
266 byte_view view(edid.data(), edid.size());
267 view.remove_prefix(kDescriptorOffset);
268
269 std::string_view displayName;
270 std::string_view serialNumber;
271 std::string_view asciiText;
272
273 constexpr size_t kDescriptorCount = 4;
274 constexpr size_t kDescriptorLength = 18;
275
276 for (size_t i = 0; i < kDescriptorCount; i++) {
277 if (view.size() < kDescriptorLength) {
278 break;
279 }
280
281 if (const auto type = getEdidDescriptorType(view)) {
282 byte_view descriptor(view.data(), kDescriptorLength);
283 descriptor.remove_prefix(kEdidHeaderLength);
284
285 switch (*type) {
286 case 0xfc:
287 displayName = parseEdidText(descriptor);
288 break;
289 case 0xfe:
290 asciiText = parseEdidText(descriptor);
291 break;
292 case 0xff:
293 serialNumber = parseEdidText(descriptor);
294 break;
295 }
296 }
297
298 view.remove_prefix(kDescriptorLength);
299 }
300
301 std::string_view modelString = displayName;
302
303 if (modelString.empty()) {
304 ALOGW("Invalid EDID: falling back to serial number due to missing display name.");
305 modelString = serialNumber;
306 }
307 if (modelString.empty()) {
308 ALOGW("Invalid EDID: falling back to ASCII text due to missing serial number.");
309 modelString = asciiText;
310 }
311 if (modelString.empty()) {
312 ALOGE("Invalid EDID: display name and fallback descriptors are missing.");
313 return {};
314 }
315
316 // Hash model string instead of using product code or (integer) serial number, since the latter
317 // have been observed to change on some displays with multiple inputs. Use a stable hash instead
318 // of std::hash which is only required to be same within a single execution of a program.
319 const uint32_t modelHash = static_cast<uint32_t>(cityHash64Len0To16(modelString));
320
321 // Parse extension blocks.
322 std::optional<Cea861ExtensionBlock> cea861Block;
323 if (edid.size() < kEdidBlockSize) {
324 ALOGW("Invalid EDID: block 0 is truncated.");
325 } else {
326 constexpr size_t kNumExtensionsOffset = 126;
327 const size_t numExtensions = edid[kNumExtensionsOffset];
328 view = byte_view(edid.data(), edid.size());
329 for (size_t blockNumber = 1; blockNumber <= numExtensions; blockNumber++) {
330 view.remove_prefix(kEdidBlockSize);
331 if (view.size() < kEdidBlockSize) {
332 ALOGW("Invalid EDID: block %zu is truncated.", blockNumber);
333 break;
334 }
335
336 const byte_view block(view.data(), kEdidBlockSize);
337 ALOGW_IF(std::accumulate(block.begin(), block.end(), static_cast<uint8_t>(0)),
338 "Invalid EDID: block %zu does not checksum.", blockNumber);
339 const uint8_t tag = block[0];
340
341 constexpr uint8_t kCea861BlockTag = 0x2;
342 if (tag == kCea861BlockTag) {
343 cea861Block = parseCea861Block(block);
344 } else {
345 ALOGV("Ignoring block number %zu with tag %x.", blockNumber, tag);
346 }
347 }
348 }
349
350 return Edid{.manufacturerId = manufacturerId,
351 .productId = productId,
352 .pnpId = *pnpId,
353 .modelHash = modelHash,
354 .displayName = displayName,
355 .manufactureOrModelYear = manufactureOrModelYear,
356 .manufactureWeek = manufactureWeek,
357 .cea861Block = cea861Block};
358 }
359
getPnpId(uint16_t manufacturerId)360 std::optional<PnpId> getPnpId(uint16_t manufacturerId) {
361 const char a = getPnpLetter<0>(manufacturerId);
362 const char b = getPnpLetter<1>(manufacturerId);
363 const char c = getPnpLetter<2>(manufacturerId);
364 return a && b && c ? std::make_optional(PnpId{a, b, c}) : std::nullopt;
365 }
366
getPnpId(PhysicalDisplayId displayId)367 std::optional<PnpId> getPnpId(PhysicalDisplayId displayId) {
368 return getPnpId(displayId.getManufacturerId());
369 }
370
parseDisplayIdentificationData(uint8_t port,const DisplayIdentificationData & data)371 std::optional<DisplayIdentificationInfo> parseDisplayIdentificationData(
372 uint8_t port, const DisplayIdentificationData& data) {
373 if (!isEdid(data)) {
374 ALOGE("Display identification data has unknown format.");
375 return {};
376 }
377
378 const auto edid = parseEdid(data);
379 if (!edid) {
380 return {};
381 }
382
383 const auto displayId = PhysicalDisplayId::fromEdid(port, edid->manufacturerId, edid->modelHash);
384 return DisplayIdentificationInfo{.id = displayId,
385 .name = std::string(edid->displayName),
386 .deviceProductInfo = buildDeviceProductInfo(*edid)};
387 }
388
getVirtualDisplayId(uint32_t id)389 PhysicalDisplayId getVirtualDisplayId(uint32_t id) {
390 return PhysicalDisplayId::fromEdid(0, kVirtualEdidManufacturerId, id);
391 }
392
cityHash64Len0To16(std::string_view sv)393 uint64_t cityHash64Len0To16(std::string_view sv) {
394 auto len = sv.length();
395 if (len > 16) {
396 ALOGE("%s called with length %zu. Only hashing the first 16 chars", __FUNCTION__, len);
397 len = 16;
398 }
399 return hash64Len0To16(sv.data(), len);
400 }
401
402 } // namespace android