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 // TODO(b/129481165): remove the #pragma below and fix conversion issues
18 #pragma clang diagnostic push
19 #pragma clang diagnostic ignored "-Wconversion"
20 
21 #undef LOG_TAG
22 #define LOG_TAG "DisplayIdentification"
23 
24 #include <algorithm>
25 #include <cctype>
26 #include <numeric>
27 #include <optional>
28 
29 #include <log/log.h>
30 
31 #include "DisplayIdentification.h"
32 
33 namespace android {
34 namespace {
35 
36 using byte_view = std::basic_string_view<uint8_t>;
37 
38 constexpr size_t kEdidBlockSize = 128;
39 constexpr size_t kEdidHeaderLength = 5;
40 
41 constexpr uint16_t kFallbackEdidManufacturerId = 0;
42 constexpr uint16_t kVirtualEdidManufacturerId = 0xffffu;
43 
getEdidDescriptorType(const byte_view & view)44 std::optional<uint8_t> getEdidDescriptorType(const byte_view& view) {
45     if (view.size() < kEdidHeaderLength || view[0] || view[1] || view[2] || view[4]) {
46         return {};
47     }
48 
49     return view[3];
50 }
51 
parseEdidText(const byte_view & view)52 std::string_view parseEdidText(const byte_view& view) {
53     std::string_view text(reinterpret_cast<const char*>(view.data()), view.size());
54     text = text.substr(0, text.find('\n'));
55 
56     if (!std::all_of(text.begin(), text.end(), ::isprint)) {
57         ALOGW("Invalid EDID: ASCII text is not printable.");
58         return {};
59     }
60 
61     return text;
62 }
63 
64 // Big-endian 16-bit value encodes three 5-bit letters where A is 0b00001.
65 template <size_t I>
getPnpLetter(uint16_t id)66 char getPnpLetter(uint16_t id) {
67     static_assert(I < 3);
68     const char letter = 'A' + (static_cast<uint8_t>(id >> ((2 - I) * 5)) & 0b00011111) - 1;
69     return letter < 'A' || letter > 'Z' ? '\0' : letter;
70 }
71 
buildDeviceProductInfo(const Edid & edid)72 DeviceProductInfo buildDeviceProductInfo(const Edid& edid) {
73     DeviceProductInfo info;
74     std::copy(edid.displayName.begin(), edid.displayName.end(), info.name.begin());
75     info.name[edid.displayName.size()] = '\0';
76 
77     const auto productId = std::to_string(edid.productId);
78     std::copy(productId.begin(), productId.end(), info.productId.begin());
79     info.productId[productId.size()] = '\0';
80     info.manufacturerPnpId = edid.pnpId;
81 
82     constexpr uint8_t kModelYearFlag = 0xff;
83     constexpr uint32_t kYearOffset = 1990;
84 
85     const auto year = edid.manufactureOrModelYear + kYearOffset;
86     if (edid.manufactureWeek == kModelYearFlag) {
87         info.manufactureOrModelDate = DeviceProductInfo::ModelYear{.year = year};
88     } else if (edid.manufactureWeek == 0) {
89         DeviceProductInfo::ManufactureYear date;
90         date.year = year;
91         info.manufactureOrModelDate = date;
92     } else {
93         DeviceProductInfo::ManufactureWeekAndYear date;
94         date.year = year;
95         date.week = edid.manufactureWeek;
96         info.manufactureOrModelDate = date;
97     }
98 
99     if (edid.cea861Block && edid.cea861Block->hdmiVendorDataBlock) {
100         const auto& address = edid.cea861Block->hdmiVendorDataBlock->physicalAddress;
101         info.relativeAddress = {address.a, address.b, address.c, address.d};
102     } else {
103         info.relativeAddress = DeviceProductInfo::NO_RELATIVE_ADDRESS;
104     }
105     return info;
106 }
107 
parseCea861Block(const byte_view & block)108 Cea861ExtensionBlock parseCea861Block(const byte_view& block) {
109     Cea861ExtensionBlock cea861Block;
110 
111     constexpr size_t kRevisionNumberOffset = 1;
112     cea861Block.revisionNumber = block[kRevisionNumberOffset];
113 
114     constexpr size_t kDetailedTimingDescriptorsOffset = 2;
115     const size_t dtdStart =
116             std::min(kEdidBlockSize, static_cast<size_t>(block[kDetailedTimingDescriptorsOffset]));
117 
118     // Parse data blocks.
119     for (size_t dataBlockOffset = 4; dataBlockOffset < dtdStart;) {
120         const uint8_t header = block[dataBlockOffset];
121         const uint8_t tag = header >> 5;
122         const size_t bodyLength = header & 0b11111;
123         constexpr size_t kDataBlockHeaderSize = 1;
124         const size_t dataBlockSize = bodyLength + kDataBlockHeaderSize;
125 
126         if (block.size() < dataBlockOffset + dataBlockSize) {
127             ALOGW("Invalid EDID: CEA 861 data block is truncated.");
128             break;
129         }
130 
131         const byte_view dataBlock(block.data() + dataBlockOffset, dataBlockSize);
132         constexpr uint8_t kVendorSpecificDataBlockTag = 0x3;
133 
134         if (tag == kVendorSpecificDataBlockTag) {
135             const uint32_t ieeeRegistrationId =
136                     dataBlock[1] | (dataBlock[2] << 8) | (dataBlock[3] << 16);
137             constexpr uint32_t kHdmiIeeeRegistrationId = 0xc03;
138 
139             if (ieeeRegistrationId == kHdmiIeeeRegistrationId) {
140                 const uint8_t a = dataBlock[4] >> 4;
141                 const uint8_t b = dataBlock[4] & 0b1111;
142                 const uint8_t c = dataBlock[5] >> 4;
143                 const uint8_t d = dataBlock[5] & 0b1111;
144                 cea861Block.hdmiVendorDataBlock =
145                         HdmiVendorDataBlock{.physicalAddress = HdmiPhysicalAddress{a, b, c, d}};
146             } else {
147                 ALOGV("Ignoring vendor specific data block for vendor with IEEE OUI %x",
148                       ieeeRegistrationId);
149             }
150         } else {
151             ALOGV("Ignoring CEA-861 data block with tag %x", tag);
152         }
153         dataBlockOffset += bodyLength + kDataBlockHeaderSize;
154     }
155 
156     return cea861Block;
157 }
158 
159 } // namespace
160 
manufacturerId() const161 uint16_t DisplayId::manufacturerId() const {
162     return static_cast<uint16_t>(value >> 40);
163 }
164 
fromEdid(uint8_t port,uint16_t manufacturerId,uint32_t modelHash)165 DisplayId DisplayId::fromEdid(uint8_t port, uint16_t manufacturerId, uint32_t modelHash) {
166     return {(static_cast<Type>(manufacturerId) << 40) | (static_cast<Type>(modelHash) << 8) | port};
167 }
168 
isEdid(const DisplayIdentificationData & data)169 bool isEdid(const DisplayIdentificationData& data) {
170     const uint8_t kMagic[] = {0, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0};
171     return data.size() >= sizeof(kMagic) &&
172             std::equal(std::begin(kMagic), std::end(kMagic), data.begin());
173 }
174 
parseEdid(const DisplayIdentificationData & edid)175 std::optional<Edid> parseEdid(const DisplayIdentificationData& edid) {
176     if (edid.size() < kEdidBlockSize) {
177         ALOGW("Invalid EDID: structure is truncated.");
178         // Attempt parsing even if EDID is malformed.
179     } else {
180         ALOGW_IF(std::accumulate(edid.begin(), edid.begin() + kEdidBlockSize,
181                                  static_cast<uint8_t>(0)),
182                  "Invalid EDID: structure does not checksum.");
183     }
184 
185     constexpr size_t kManufacturerOffset = 8;
186     if (edid.size() < kManufacturerOffset + sizeof(uint16_t)) {
187         ALOGE("Invalid EDID: manufacturer ID is truncated.");
188         return {};
189     }
190 
191     // Plug and play ID encoded as big-endian 16-bit value.
192     const uint16_t manufacturerId =
193             (edid[kManufacturerOffset] << 8) | edid[kManufacturerOffset + 1];
194 
195     const auto pnpId = getPnpId(manufacturerId);
196     if (!pnpId) {
197         ALOGE("Invalid EDID: manufacturer ID is not a valid PnP ID.");
198         return {};
199     }
200 
201     constexpr size_t kProductIdOffset = 10;
202     if (edid.size() < kProductIdOffset + sizeof(uint16_t)) {
203         ALOGE("Invalid EDID: product ID is truncated.");
204         return {};
205     }
206     const uint16_t productId = edid[kProductIdOffset] | (edid[kProductIdOffset + 1] << 8);
207 
208     constexpr size_t kManufactureWeekOffset = 16;
209     if (edid.size() < kManufactureWeekOffset + sizeof(uint8_t)) {
210         ALOGE("Invalid EDID: manufacture week is truncated.");
211         return {};
212     }
213     const uint8_t manufactureWeek = edid[kManufactureWeekOffset];
214     ALOGW_IF(0x37 <= manufactureWeek && manufactureWeek <= 0xfe,
215              "Invalid EDID: week of manufacture cannot be in the range [0x37, 0xfe].");
216 
217     constexpr size_t kManufactureYearOffset = 17;
218     if (edid.size() < kManufactureYearOffset + sizeof(uint8_t)) {
219         ALOGE("Invalid EDID: manufacture year is truncated.");
220         return {};
221     }
222     const uint8_t manufactureOrModelYear = edid[kManufactureYearOffset];
223     ALOGW_IF(manufactureOrModelYear <= 0xf,
224              "Invalid EDID: model year or manufacture year cannot be in the range [0x0, 0xf].");
225 
226     constexpr size_t kDescriptorOffset = 54;
227     if (edid.size() < kDescriptorOffset) {
228         ALOGE("Invalid EDID: descriptors are missing.");
229         return {};
230     }
231 
232     byte_view view(edid.data(), edid.size());
233     view.remove_prefix(kDescriptorOffset);
234 
235     std::string_view displayName;
236     std::string_view serialNumber;
237     std::string_view asciiText;
238 
239     constexpr size_t kDescriptorCount = 4;
240     constexpr size_t kDescriptorLength = 18;
241     static_assert(kDescriptorLength - kEdidHeaderLength < DeviceProductInfo::TEXT_BUFFER_SIZE);
242 
243     for (size_t i = 0; i < kDescriptorCount; i++) {
244         if (view.size() < kDescriptorLength) {
245             break;
246         }
247 
248         if (const auto type = getEdidDescriptorType(view)) {
249             byte_view descriptor(view.data(), kDescriptorLength);
250             descriptor.remove_prefix(kEdidHeaderLength);
251 
252             switch (*type) {
253                 case 0xfc:
254                     displayName = parseEdidText(descriptor);
255                     break;
256                 case 0xfe:
257                     asciiText = parseEdidText(descriptor);
258                     break;
259                 case 0xff:
260                     serialNumber = parseEdidText(descriptor);
261                     break;
262             }
263         }
264 
265         view.remove_prefix(kDescriptorLength);
266     }
267 
268     std::string_view modelString = displayName;
269 
270     if (modelString.empty()) {
271         ALOGW("Invalid EDID: falling back to serial number due to missing display name.");
272         modelString = serialNumber;
273     }
274     if (modelString.empty()) {
275         ALOGW("Invalid EDID: falling back to ASCII text due to missing serial number.");
276         modelString = asciiText;
277     }
278     if (modelString.empty()) {
279         ALOGE("Invalid EDID: display name and fallback descriptors are missing.");
280         return {};
281     }
282 
283     // Hash model string instead of using product code or (integer) serial number, since the latter
284     // have been observed to change on some displays with multiple inputs.
285     const auto modelHash = static_cast<uint32_t>(std::hash<std::string_view>()(modelString));
286 
287     // Parse extension blocks.
288     std::optional<Cea861ExtensionBlock> cea861Block;
289     if (edid.size() < kEdidBlockSize) {
290         ALOGW("Invalid EDID: block 0 is truncated.");
291     } else {
292         constexpr size_t kNumExtensionsOffset = 126;
293         const size_t numExtensions = edid[kNumExtensionsOffset];
294         view = byte_view(edid.data(), edid.size());
295         for (size_t blockNumber = 1; blockNumber <= numExtensions; blockNumber++) {
296             view.remove_prefix(kEdidBlockSize);
297             if (view.size() < kEdidBlockSize) {
298                 ALOGW("Invalid EDID: block %zu is truncated.", blockNumber);
299                 break;
300             }
301 
302             const byte_view block(view.data(), kEdidBlockSize);
303             ALOGW_IF(std::accumulate(block.begin(), block.end(), static_cast<uint8_t>(0)),
304                      "Invalid EDID: block %zu does not checksum.", blockNumber);
305             const uint8_t tag = block[0];
306 
307             constexpr uint8_t kCea861BlockTag = 0x2;
308             if (tag == kCea861BlockTag) {
309                 cea861Block = parseCea861Block(block);
310             } else {
311                 ALOGV("Ignoring block number %zu with tag %x.", blockNumber, tag);
312             }
313         }
314     }
315 
316     return Edid{.manufacturerId = manufacturerId,
317                 .productId = productId,
318                 .pnpId = *pnpId,
319                 .modelHash = modelHash,
320                 .displayName = displayName,
321                 .manufactureOrModelYear = manufactureOrModelYear,
322                 .manufactureWeek = manufactureWeek,
323                 .cea861Block = cea861Block};
324 }
325 
getPnpId(uint16_t manufacturerId)326 std::optional<PnpId> getPnpId(uint16_t manufacturerId) {
327     const char a = getPnpLetter<0>(manufacturerId);
328     const char b = getPnpLetter<1>(manufacturerId);
329     const char c = getPnpLetter<2>(manufacturerId);
330     return a && b && c ? std::make_optional(PnpId{a, b, c}) : std::nullopt;
331 }
332 
getPnpId(DisplayId displayId)333 std::optional<PnpId> getPnpId(DisplayId displayId) {
334     return getPnpId(displayId.manufacturerId());
335 }
336 
parseDisplayIdentificationData(uint8_t port,const DisplayIdentificationData & data)337 std::optional<DisplayIdentificationInfo> parseDisplayIdentificationData(
338         uint8_t port, const DisplayIdentificationData& data) {
339     if (!isEdid(data)) {
340         ALOGE("Display identification data has unknown format.");
341         return {};
342     }
343 
344     const auto edid = parseEdid(data);
345     if (!edid) {
346         return {};
347     }
348 
349     const auto displayId = DisplayId::fromEdid(port, edid->manufacturerId, edid->modelHash);
350     return DisplayIdentificationInfo{.id = displayId,
351                                      .name = std::string(edid->displayName),
352                                      .deviceProductInfo = buildDeviceProductInfo(*edid)};
353 }
354 
getFallbackDisplayId(uint8_t port)355 DisplayId getFallbackDisplayId(uint8_t port) {
356     return DisplayId::fromEdid(port, kFallbackEdidManufacturerId, 0);
357 }
358 
getVirtualDisplayId(uint32_t id)359 DisplayId getVirtualDisplayId(uint32_t id) {
360     return DisplayId::fromEdid(0, kVirtualEdidManufacturerId, id);
361 }
362 
363 } // namespace android
364 
365 // TODO(b/129481165): remove the #pragma below and fix conversion issues
366 #pragma clang diagnostic pop // ignored "-Wconversion"
367