Debian Codegraph @

utils/edid-decode/edid-decode.cpp

raw
1 // SPDX-License-Identifier: MIT
2 /*
3 * Copyright 2006-2012 Red Hat, Inc.
4 * Copyright 2018-2020 Cisco Systems, Inc. and/or its affiliates. All rights reserved.
5 *
6 * Author: Adam Jackson <[email protected]>
7 * Maintainer: Hans Verkuil <[email protected]>
8 */
9
10 #include <ctype.h>
11 #include <fcntl.h>
12 #include <getopt.h>
13 #include <math.h>
14 #include <stdarg.h>
15 #include <stdio.h>
16 #include <stdlib.h>
17 #include <unistd.h>
18
19 #include "edid-decode.h"
20
21 #define STR(x) #x
22 #define STRING(x) STR(x)
23
24 static edid_state state;
25
26 static unsigned char edid[EDID_PAGE_SIZE * EDID_MAX_BLOCKS];
27 static bool odd_hex_digits;
28
29 enum output_format {
30 OUT_FMT_DEFAULT,
31 OUT_FMT_HEX,
32 OUT_FMT_RAW,
33 OUT_FMT_CARRAY,
34 OUT_FMT_XML,
35 };
36
37 /*
38 * Options
39 * Please keep in alphabetical order of the short option.
40 * That makes it easier to see which options are still free.
41 */
42 enum Option {
43 OptI2CAdapter = 'a',
44 OptCheck = 'c',
45 OptCheckInline = 'C',
46 OptEld = 'E',
47 OptFBModeTimings = 'F',
48 OptHelp = 'h',
49 OptOnlyHexDump = 'H',
50 OptInfoFrame = 'I',
51 OptLongTimings = 'L',
52 OptNativeResolution = 'n',
53 OptNTSC = 'N',
54 OptOutputFormat = 'o',
55 OptPreferredTimings = 'p',
56 OptPhysicalAddress = 'P',
57 OptSkipHexDump = 's',
58 OptShortTimings = 'S',
59 OptUTF8 = 'u',
60 OptV4L2Timings = 'V',
61 OptXModeLineTimings = 'X',
62 OptSkipSHA = 128,
63 OptHideSerialNumbers,
64 OptReplaceUniqueIDs,
65 OptVersion,
66 OptDiag,
67 OptI2CEDID,
68 OptI2CHDCP,
69 OptI2CHDCPRi,
70 OptI2CTestReliability,
71 OptSTD,
72 OptDMT,
73 OptVIC,
74 OptHDMIVIC,
75 OptCVT,
76 OptGTF,
77 OptOVT,
78 OptListEstTimings,
79 OptListDMTs,
80 OptListVICs,
81 OptListHDMIVICs,
82 OptListRIDTimings,
83 OptListRIDs,
84 OptLast = 256
85 };
86
87 static char options[OptLast];
88
89 #ifndef __EMSCRIPTEN__
90 static struct option long_options[] = {
91 { "help", no_argument, 0, OptHelp },
92 { "output-format", required_argument, 0, OptOutputFormat },
93 { "native-resolution", no_argument, 0, OptNativeResolution },
94 { "preferred-timings", no_argument, 0, OptPreferredTimings },
95 { "physical-address", no_argument, 0, OptPhysicalAddress },
96 { "skip-hex-dump", no_argument, 0, OptSkipHexDump },
97 { "only-hex-dump", no_argument, 0, OptOnlyHexDump },
98 { "skip-sha", no_argument, 0, OptSkipSHA },
99 { "hide-serial-numbers", no_argument, 0, OptHideSerialNumbers },
100 { "replace-unique-ids", no_argument, 0, OptReplaceUniqueIDs },
101 { "utf8", no_argument, 0, OptUTF8 },
102 { "version", no_argument, 0, OptVersion },
103 { "check-inline", no_argument, 0, OptCheckInline },
104 { "check", no_argument, 0, OptCheck },
105 { "short-timings", no_argument, 0, OptShortTimings },
106 { "long-timings", no_argument, 0, OptLongTimings },
107 { "ntsc", no_argument, 0, OptNTSC },
108 { "xmodeline", no_argument, 0, OptXModeLineTimings },
109 { "fbmode", no_argument, 0, OptFBModeTimings },
110 { "v4l2-timings", no_argument, 0, OptV4L2Timings },
111 { "diagonal", required_argument, 0, OptDiag },
112 #ifdef __HAS_I2C_DEV__
113 { "i2c-adapter", required_argument, 0, OptI2CAdapter },
114 { "i2c-edid", no_argument, 0, OptI2CEDID },
115 { "i2c-hdcp", no_argument, 0, OptI2CHDCP },
116 { "i2c-hdcp-ri", required_argument, 0, OptI2CHDCPRi },
117 { "i2c-test-reliability", optional_argument, 0, OptI2CTestReliability },
118 #endif
119 { "std", required_argument, 0, OptSTD },
120 { "dmt", required_argument, 0, OptDMT },
121 { "vic", required_argument, 0, OptVIC },
122 { "hdmi-vic", required_argument, 0, OptHDMIVIC },
123 { "cvt", required_argument, 0, OptCVT },
124 { "gtf", required_argument, 0, OptGTF },
125 { "ovt", required_argument, 0, OptOVT },
126 { "list-established-timings", no_argument, 0, OptListEstTimings },
127 { "list-dmts", no_argument, 0, OptListDMTs },
128 { "list-vics", no_argument, 0, OptListVICs },
129 { "list-hdmi-vics", no_argument, 0, OptListHDMIVICs },
130 { "list-rid-timings", required_argument, 0, OptListRIDTimings },
131 { "list-rids", no_argument, 0, OptListRIDs },
132 { "infoframe", required_argument, 0, OptInfoFrame },
133 { "eld", required_argument, 0, OptEld },
134 { 0, 0, 0, 0 }
135 };
136
137 static void usage(void)
138 {
139 printf("Usage: edid-decode <options> [in [out]]\n"
140 " [in] EDID file to parse. Read from standard input if none given\n"
141 " and neither --infoframe nor --eld was not used, or if the\n"
142 " input filename is '-'.\n"
143 " [out] Output the read EDID to this file. Write to standard output\n"
144 " if the output filename is '-'.\n"
145 "\nOptions:\n"
146 " -o, --output-format <fmt>\n"
147 " If [out] is specified, then write the EDID in this format.\n"
148 " <fmt> is one of:\n"
149 " hex: hex numbers in ascii text (default for stdout)\n"
150 " raw: binary data (default unless writing to stdout)\n"
151 " carray: c-program struct\n"
152 " xml: XML data\n"
153 " -c, --check Check if the EDID conforms to the standards, failures and\n"
154 " warnings are reported at the end.\n"
155 " -C, --check-inline Check if the EDID conforms to the standards, failures and\n"
156 " warnings are reported inline.\n"
157 " -n, --native-resolution Report the native resolution.\n"
158 " -p, --preferred-timings Report the preferred timings.\n"
159 " -P, --physical-address Only report the CEC physical address.\n"
160 " -S, --short-timings Report all video timings in a short format.\n"
161 " -L, --long-timings Report all video timings in a long format.\n"
162 " -N, --ntsc Report the video timings suitable for NTSC-based video.\n"
163 " -X, --xmodeline Report all long video timings in Xorg.conf format.\n"
164 " -F, --fbmode Report all long video timings in fb.modes format.\n"
165 " -V, --v4l2-timings Report all long video timings in v4l2-dv-timings.h format.\n"
166 " -s, --skip-hex-dump Skip the initial hex dump of the EDID.\n"
167 " -H, --only-hex-dump Only output the hex dump of the EDID.\n"
168 " --skip-sha Skip the SHA report.\n"
169 " --hide-serial-numbers Hide serial numbers with '...'.\n"
170 " --replace-unique-ids Replace unique IDs (serial numbers, dates, Container IDs) with fixed values.\n"
171 " -u, --utf8 Convert strings in EDIDs to UTF-8.\n"
172 " --version Show the edid-decode version (SHA).\n"
173 " --diagonal <inches> Set the display's diagonal in inches.\n"
174 #ifdef __HAS_I2C_DEV__
175 " -a, --i2c-adapter <dev> Use <dev> to access the DDC lines.\n"
176 " If <dev> starts with a digit, then /dev/i2c-<dev> is used.\n"
177 " --i2c-edid Read the EDID from the DDC lines.\n"
178 " --i2c-hdcp Read the HDCP from the DDC lines.\n"
179 " --i2c-hdcp-ri=<t> Read and print the HDCP Ri information every <t> seconds.\n"
180 " --i2c-test-reliability [duration=<secs>][,sleep=<msecs>]\n"
181 " Read the EDID continuously for <secs> seconds (default=0=forever), with a sleep\n"
182 " of <msecs> milliseconds (default value is 50 ms) in between each read.\n"
183 " Report a FAIL if there are mismatches between EDIDs.\n"
184 " This tests the i2c communication towards the display.\n"
185 #endif
186 " --std <byte1>,<byte2> Show the standard timing represented by these two bytes.\n"
187 " --dmt <dmt> Show the timings for the DMT with the given DMT ID.\n"
188 " --vic <vic> Show the timings for this VIC.\n"
189 " --hdmi-vic <hdmivic> Show the timings for this HDMI VIC.\n"
190 " --cvt w=<width>,h=<height>,fps=<fps>[,rb=<rb>][,interlaced][,overscan][,alt][,hblank=<hblank>][,vblank=<vblank>][,early-vsync]\n"
191 " Calculate the CVT timings for the given format.\n"
192 " <fps> is frames per second for progressive timings,\n"
193 " or fields per second for interlaced timings.\n"
194 " <rb> can be 0 (no reduced blanking, default), or\n"
195 " 1-3 for the reduced blanking version.\n"
196 " If 'interlaced' is given, then this is an interlaced format.\n"
197 " If 'overscan' is given, then this is an overscanned format.\n"
198 " If 'alt' is given and <rb>=2, then report the timings\n"
199 " optimized for video: 1000 / 1001 * <fps>.\n"
200 " If 'alt' is given and <rb>=3, then the horizontal blanking\n"
201 " is 160 instead of 80 pixels.\n"
202 " If 'hblank' is given and <rb>=3, then the horizontal blanking\n"
203 " is <hblank> pixels (range of 80-200), overriding 'alt'.\n"
204 " If 'vblank' is given and <rb>=3, then the vertical blanking\n"
205 " time is <vblank> microseconds (range of 460-705 or 300-440).\n"
206 " If 'early-vsync' is given and <rb=3>, then select early vsync.\n"
207 " --gtf w=<width>,h=<height>[,fps=<fps>][,horfreq=<horfreq>][,pixclk=<pixclk>][,interlaced]\n"
208 " [,overscan][,secondary][,C=<c>][,M=<m>][,K=<k>][,J=<j>]\n"
209 " Calculate the GTF timings for the given format.\n"
210 " <fps> is frames per second for progressive timings,\n"
211 " or fields per second for interlaced timings.\n"
212 " <horfreq> is the horizontal frequency in kHz.\n"
213 " <pixclk> is the pixel clock frequency in MHz.\n"
214 " Only one of fps, horfreq or pixclk must be given.\n"
215 " If 'interlaced' is given, then this is an interlaced format.\n"
216 " If 'overscan' is given, then this is an overscanned format.\n"
217 " If 'secondary' is given, then the secondary GTF is used for\n"
218 " reduced blanking, where <c>, <m>, <k> and <j> are parameters\n"
219 " for the secondary curve.\n"
220 " --ovt (rid=<rid>|w=<width>,h=<height>),fps=<fps>\n"
221 " Calculate the OVT timings for the given format.\n"
222 " Either specify a RID or explicitly specify width and height.\n"
223 " --list-established-timings List all known Established Timings.\n"
224 " --list-dmts List all known DMTs.\n"
225 " --list-vics List all known VICs.\n"
226 " --list-hdmi-vics List all known HDMI VICs.\n"
227 " --list-rids List all known RIDs.\n"
228 " --list-rid-timings <rid> List all timings for RID <rid> or all known RIDs if <rid> is 0.\n"
229 " -I, --infoframe <file> Parse the InfoFrame from <file> (or stdin if '-' was specified) that was sent to this display.\n"
230 " This option can be specified multiple times for different InfoFrame files.\n"
231 " -E, --eld <file> Parse the EDID-Like Data, ELD from <file> (or stdin if '-' was specified).\n"
232 " This option can be specified multiple times for different ELD files.\n"
233 " -h, --help Display this help message.\n");
234 }
235 #endif
236
237 static std::string s_msgs[EDID_MAX_BLOCKS + 1][2];
238
239 static void print_version()
240 {
241 #define STR(x) #x
242 #define STRING(x) STR(x)
243 #ifndef __EMSCRIPTEN__
244 printf("edid-decode %s%s\n", PACKAGE_VERSION, STRING(GIT_COMMIT_CNT));
245 #endif
246 if (strlen(STRING(GIT_SHA)))
247 printf("edid-decode SHA: %s %s\n", STRING(GIT_SHA), STRING(GIT_COMMIT_DATE));
248 }
249
250 void msg(bool is_warn, const char *fmt, ...)
251 {
252 char buf[1024] = "";
253 va_list ap;
254
255 va_start(ap, fmt);
256 vsprintf(buf, fmt, ap);
257 va_end(ap);
258
259 if (is_warn)
260 state.warnings++;
261 else
262 state.failures++;
263 if (state.data_block.empty())
264 s_msgs[state.block_nr][is_warn] += std::string(" ") + buf;
265 else
266 s_msgs[state.block_nr][is_warn] += " " + state.data_block + ": " + buf;
267
268 if (options[OptCheckInline])
269 printf("%s: %s", is_warn ? "WARN" : "FAIL", buf);
270 }
271
272 static void show_msgs(bool is_warn)
273 {
274 printf("\n%s:\n\n", is_warn ? "Warnings" : "Failures");
275 for (unsigned i = 0; i < state.num_blocks; i++) {
276 if (s_msgs[i][is_warn].empty())
277 continue;
278 printf("Block %u, %s:\n%s",
279 i, block_name(edid[i * EDID_PAGE_SIZE]).c_str(),
280 s_msgs[i][is_warn].c_str());
281 }
282 if (s_msgs[EDID_MAX_BLOCKS][is_warn].empty())
283 return;
284 printf("EDID:\n%s",
285 s_msgs[EDID_MAX_BLOCKS][is_warn].c_str());
286 }
287
288
289 void replace_checksum(unsigned char *x, size_t len)
290 {
291 unsigned char sum = 0;
292 unsigned i;
293
294 for (i = 0; i < len - 1; i++)
295 sum += x[i];
296 x[len - 1] = -sum & 0xff;
297 }
298
299 void do_checksum(const char *prefix, const unsigned char *x, size_t len, size_t checksum_pos,
300 unsigned unused_bytes)
301 {
302 unsigned char check = x[checksum_pos];
303 unsigned char sum = 0;
304 unsigned i;
305
306 for (i = 0; i < len; i++) {
307 if (i != checksum_pos)
308 sum += x[i];
309 }
310
311 printf("%sChecksum: 0x%02hhx", prefix, check);
312 if ((unsigned char)(check + sum) != 0) {
313 printf(" (should be 0x%02x)", -sum & 0xff);
314 fail("Invalid checksum 0x%02x (should be 0x%02x).\n",
315 check, -sum & 0xff);
316 }
317 if (unused_bytes)
318 printf(" Unused space in Extension Block: %u byte%s",
319 unused_bytes, unused_bytes > 1 ? "s" : "");
320 printf("\n");
321 }
322
323 unsigned gcd(unsigned a, unsigned b)
324 {
325 while (b) {
326 unsigned t = b;
327
328 b = a % b;
329 a = t;
330 }
331 return a;
332 }
333
334 void calc_ratio(struct timings *t)
335 {
336 unsigned d = gcd(t->hact, t->vact);
337
338 if (d == 0) {
339 t->hratio = t->vratio = 0;
340 return;
341 }
342 t->hratio = t->hact / d;
343 t->vratio = t->vact / d;
344
345 if (t->hratio == 8 && t->vratio == 5) {
346 t->hratio = 16;
347 t->vratio = 10;
348 }
349 }
350
351 unsigned calc_fps(const struct timings *t)
352 {
353 unsigned vact = t->vact;
354 unsigned vbl = t->vfp + t->vsync + t->vbp + 2 * t->vborder;
355 unsigned hbl = t->hfp + t->hsync + t->hbp + 2 * t->hborder;
356 unsigned htotal = t->hact + hbl;
357
358 if (t->interlaced)
359 vact /= 2;
360
361 double vtotal = vact + vbl;
362
363 if (t->even_vtotal)
364 vtotal = vact + t->vfp + t->vsync + t->vbp;
365 else if (t->interlaced)
366 vtotal = vact + t->vfp + t->vsync + t->vbp + 0.5;
367
368 return t->pixclk_khz * 1000.0 / (htotal * vtotal);
369 }
370
371 std::string edid_state::dtd_type(unsigned cnt)
372 {
373 unsigned len = std::to_string(cta.preparsed_total_dtds).length();
374 char buf[16];
375 sprintf(buf, "DTD %*u", len, cnt);
376 return buf;
377 }
378
379 bool match_timings(const timings &t1, const timings &t2)
380 {
381 if (t1.hact != t2.hact ||
382 t1.vact != t2.vact ||
383 t1.rb != t2.rb ||
384 t1.interlaced != t2.interlaced ||
385 t1.hfp != t2.hfp ||
386 t1.hbp != t2.hbp ||
387 t1.hsync != t2.hsync ||
388 t1.pos_pol_hsync != t2.pos_pol_hsync ||
389 t1.hratio != t2.hratio ||
390 t1.vfp != t2.vfp ||
391 t1.vbp != t2.vbp ||
392 t1.vsync != t2.vsync ||
393 t1.pos_pol_vsync != t2.pos_pol_vsync ||
394 t1.vratio != t2.vratio ||
395 t1.pixclk_khz != t2.pixclk_khz)
396 return false;
397 return true;
398 }
399
400 static void or_str(std::string &s, const std::string &flag, unsigned &num_flags)
401 {
402 if (!num_flags)
403 s = flag;
404 else if (num_flags % 2 == 0)
405 s = s + " | \\\n\t\t" + flag;
406 else
407 s = s + " | " + flag;
408 num_flags++;
409 }
410
411 /*
412 * Return true if the timings are a close, but not identical,
413 * match. The only differences allowed are polarities and
414 * porches and syncs, provided the total blanking remains the
415 * same.
416 */
417 bool timings_close_match(const timings &t1, const timings &t2)
418 {
419 // We don't want to deal with borders, you're on your own
420 // if you are using those.
421 if (t1.hborder || t1.vborder ||
422 t2.hborder || t2.vborder)
423 return false;
424 if (t1.hact != t2.hact || t1.vact != t2.vact ||
425 t1.interlaced != t2.interlaced ||
426 t1.pixclk_khz != t2.pixclk_khz ||
427 t1.hfp + t1.hsync + t1.hbp != t2.hfp + t2.hsync + t2.hbp ||
428 t1.vfp + t1.vsync + t1.vbp != t2.vfp + t2.vsync + t2.vbp)
429 return false;
430 if (t1.hfp == t2.hfp &&
431 t1.hsync == t2.hsync &&
432 t1.hbp == t2.hbp &&
433 t1.pos_pol_hsync == t2.pos_pol_hsync &&
434 t1.vfp == t2.vfp &&
435 t1.vsync == t2.vsync &&
436 t1.vbp == t2.vbp &&
437 t1.pos_pol_vsync == t2.pos_pol_vsync)
438 return false;
439 return true;
440 }
441
442 static void print_modeline(unsigned indent, const struct timings *t, double refresh)
443 {
444 unsigned offset = (!t->even_vtotal && t->interlaced) ? 1 : 0;
445 unsigned hfp = t->hborder + t->hfp;
446 unsigned hbp = t->hborder + t->hbp;
447 unsigned vfp = t->vborder + t->vfp;
448 unsigned vbp = t->vborder + t->vbp;
449
450 printf("%*sModeline \"%ux%u_%.2f%s\" %.3f %u %u %u %u %u %u %u %u %cHSync",
451 indent, "",
452 t->hact, t->vact, refresh,
453 t->interlaced ? "i" : "", t->pixclk_khz / 1000.0,
454 t->hact, t->hact + hfp, t->hact + hfp + t->hsync,
455 t->hact + hfp + t->hsync + hbp,
456 t->vact, t->vact + vfp, t->vact + vfp + t->vsync,
457 t->vact + vfp + t->vsync + vbp + offset,
458 t->pos_pol_hsync ? '+' : '-');
459 if (!t->no_pol_vsync)
460 printf(" %cVSync", t->pos_pol_vsync ? '+' : '-');
461 if (t->interlaced)
462 printf(" Interlace");
463 printf("\n");
464 }
465
466 static void print_fbmode(unsigned indent, const struct timings *t,
467 double refresh, double hor_freq_khz)
468 {
469 printf("%*smode \"%ux%u-%u%s\"\n",
470 indent, "",
471 t->hact, t->vact,
472 (unsigned)(0.5 + (t->interlaced ? refresh / 2.0 : refresh)),
473 t->interlaced ? "-lace" : "");
474 printf("%*s# D: %.2f MHz, H: %.3f kHz, V: %.2f Hz\n",
475 indent + 8, "",
476 t->pixclk_khz / 1000.0, hor_freq_khz, refresh);
477 printf("%*sgeometry %u %u %u %u 32\n",
478 indent + 8, "",
479 t->hact, t->vact, t->hact, t->vact);
480 unsigned mult = t->interlaced ? 2 : 1;
481 unsigned offset = !t->even_vtotal && t->interlaced;
482 unsigned hfp = t->hborder + t->hfp;
483 unsigned hbp = t->hborder + t->hbp;
484 unsigned vfp = t->vborder + t->vfp;
485 unsigned vbp = t->vborder + t->vbp;
486 printf("%*stimings %llu %d %d %d %u %u %u\n",
487 indent + 8, "",
488 (unsigned long long)(1000000000.0 / (double)(t->pixclk_khz) + 0.5),
489 hbp, hfp, mult * vbp, mult * vfp + offset, t->hsync, mult * t->vsync);
490 if (t->interlaced)
491 printf("%*slaced true\n", indent + 8, "");
492 if (t->pos_pol_hsync)
493 printf("%*shsync high\n", indent + 8, "");
494 if (t->pos_pol_vsync)
495 printf("%*svsync high\n", indent + 8, "");
496 printf("%*sendmode\n", indent, "");
497 }
498
499 static void print_v4l2_timing(const struct timings *t,
500 double refresh, const char *type)
501 {
502 printf("\t#define V4L2_DV_BT_%uX%u%c%u_%02u { \\\n",
503 t->hact, t->vact, t->interlaced ? 'I' : 'P',
504 (unsigned)refresh, (unsigned)(0.5 + 100.0 * (refresh - (unsigned)refresh)));
505 printf("\t\t.type = V4L2_DV_BT_656_1120, \\\n");
506 printf("\t\tV4L2_INIT_BT_TIMINGS(%u, %u, %u, ",
507 t->hact, t->vact, t->interlaced);
508 if (!t->pos_pol_hsync && !t->pos_pol_vsync)
509 printf("0, \\\n");
510 else if (t->pos_pol_hsync && t->pos_pol_vsync)
511 printf("\\\n\t\t\tV4L2_DV_HSYNC_POS_POL | V4L2_DV_VSYNC_POS_POL, \\\n");
512 else if (t->pos_pol_hsync)
513 printf("V4L2_DV_HSYNC_POS_POL, \\\n");
514 else
515 printf("V4L2_DV_VSYNC_POS_POL, \\\n");
516 unsigned hfp = t->hborder + t->hfp;
517 unsigned hbp = t->hborder + t->hbp;
518 unsigned vfp = t->vborder + t->vfp;
519 unsigned vbp = t->vborder + t->vbp;
520 printf("\t\t\t%lluULL, %d, %u, %d, %u, %u, %d, %u, %u, %d, \\\n",
521 t->pixclk_khz * 1000ULL, hfp, t->hsync, hbp,
522 vfp, t->vsync, vbp,
523 t->interlaced ? vfp : 0,
524 t->interlaced ? t->vsync : 0,
525 t->interlaced ? vbp + !t->even_vtotal : 0);
526
527 std::string flags;
528 unsigned num_flags = 0;
529 unsigned vic = 0;
530 unsigned hdmi_vic = 0;
531 const char *std = "0";
532
533 if (t->interlaced && !t->even_vtotal)
534 or_str(flags, "V4L2_DV_FL_HALF_LINE", num_flags);
535 if (!memcmp(type, "VIC", 3)) {
536 or_str(flags, "V4L2_DV_FL_HAS_CEA861_VIC", num_flags);
537 or_str(flags, "V4L2_DV_FL_IS_CE_VIDEO", num_flags);
538 vic = strtoul(type + 4, 0, 0);
539 }
540 if (!memcmp(type, "HDMI VIC", 8)) {
541 or_str(flags, "V4L2_DV_FL_HAS_HDMI_VIC", num_flags);
542 or_str(flags, "V4L2_DV_FL_IS_CE_VIDEO", num_flags);
543 hdmi_vic = strtoul(type + 9, 0, 0);
544 vic = hdmi_vic_to_vic(hdmi_vic);
545 if (vic)
546 or_str(flags, "V4L2_DV_FL_HAS_CEA861_VIC", num_flags);
547 }
548 if (vic && (fmod(refresh, 6)) == 0.0)
549 or_str(flags, "V4L2_DV_FL_CAN_REDUCE_FPS", num_flags);
550 if (t->rb)
551 or_str(flags, "V4L2_DV_FL_REDUCED_BLANKING", num_flags);
552 if (t->hratio && t->vratio)
553 or_str(flags, "V4L2_DV_FL_HAS_PICTURE_ASPECT", num_flags);
554
555 if (!memcmp(type, "VIC", 3) || !memcmp(type, "HDMI VIC", 8))
556 std = "V4L2_DV_BT_STD_CEA861";
557 else if (!memcmp(type, "DMT", 3))
558 std = "V4L2_DV_BT_STD_DMT";
559 else if (!memcmp(type, "CVT", 3))
560 std = "V4L2_DV_BT_STD_CVT";
561 else if (!memcmp(type, "GTF", 3))
562 std = "V4L2_DV_BT_STD_GTF";
563 printf("\t\t\t%s, \\\n", std);
564 printf("\t\t\t%s, \\\n", flags.empty() ? "0" : flags.c_str());
565 printf("\t\t\t{ %u, %u }, %u, %u) \\\n",
566 t->hratio, t->vratio, vic, hdmi_vic);
567 printf("\t}\n");
568 }
569
570 static void print_detailed_timing(unsigned indent, const struct timings *t)
571 {
572 printf("%*sHfront %4d Hsync %3u Hback %4d Hpol %s",
573 indent, "",
574 t->hfp, t->hsync, t->hbp, t->pos_pol_hsync ? "P" : "N");
575 if (t->hborder)
576 printf(" Hborder %u", t->hborder);
577 printf("\n");
578
579 printf("%*sVfront %4u Vsync %3u Vback %4d",
580 indent, "", t->vfp, t->vsync, t->vbp);
581 if (!t->no_pol_vsync)
582 printf(" Vpol %s", t->pos_pol_vsync ? "P" : "N");
583 if (t->vborder)
584 printf(" Vborder %u", t->vborder);
585 if (t->even_vtotal) {
586 printf(" Both Fields");
587 } else if (t->interlaced) {
588 printf(" Vfront +0.5 Odd Field\n");
589 printf("%*sVfront %4d Vsync %3u Vback %4d",
590 indent, "", t->vfp, t->vsync, t->vbp);
591 if (!t->no_pol_vsync)
592 printf(" Vpol %s", t->pos_pol_vsync ? "P" : "N");
593 if (t->vborder)
594 printf(" Vborder %u", t->vborder);
595 printf(" Vback +0.5 Even Field");
596 }
597 printf("\n");
598 }
599
600 bool edid_state::print_timings(const char *prefix, const struct timings *t,
601 const char *type, const char *flags,
602 bool detailed, bool do_checks, unsigned ntsc)
603 {
604 if (!t) {
605 // Should not happen
606 if (do_checks)
607 fail("Unknown video timings.\n");
608 return false;
609 }
610
611 if (detailed && options[OptShortTimings])
612 detailed = false;
613 if (options[OptLongTimings])
614 detailed = true;
615
616 unsigned vact = t->vact;
617 unsigned hbl = t->hfp + t->hsync + t->hbp + 2 * t->hborder;
618 unsigned vbl = t->vfp + t->vsync + t->vbp + 2 * t->vborder;
619 unsigned htotal = t->hact + hbl;
620 double hor_freq_khz = htotal ? (double)t->pixclk_khz / htotal : 0;
621
622 if (t->interlaced)
623 vact /= 2;
624
625 double out_hor_freq_khz = hor_freq_khz;
626 if (t->ycbcr420)
627 hor_freq_khz /= 2;
628
629 double vtotal = vact + vbl;
630
631 bool ok = true;
632
633 if (!t->hact || !hbl || !t->hfp || !t->hsync ||
634 !vact || !vbl || (!t->vfp && !t->interlaced && !t->even_vtotal) || !t->vsync) {
635 if (do_checks)
636 fail("0 values in the video timing:\n"
637 " Horizontal Active/Blanking %u/%u\n"
638 " Horizontal Frontporch/Sync Width %u/%u\n"
639 " Vertical Active/Blanking %u/%u\n"
640 " Vertical Frontporch/Sync Width %u/%u\n",
641 t->hact, hbl, t->hfp, t->hsync, vact, vbl, t->vfp, t->vsync);
642 ok = false;
643 }
644
645 if (t->even_vtotal)
646 vtotal = vact + t->vfp + t->vsync + t->vbp;
647 else if (t->interlaced)
648 vtotal = vact + t->vfp + t->vsync + t->vbp + 0.5;
649
650 double refresh = t->pixclk_khz * 1000.0 / (htotal * vtotal);
651 double pixclk = t->pixclk_khz * 1000.0;
652 if (((ntsc > 1 && options[OptNTSC]) || ntsc == 1) && fmod(refresh, 6.0) == 0) {
653 const double ntsc_fact = 1000.0 / 1001.0;
654 pixclk *= ntsc_fact;
655 refresh *= ntsc_fact;
656 out_hor_freq_khz *= ntsc_fact;
657 }
658
659 std::string s;
660 unsigned rb = t->rb & ~RB_ALT;
661 if (rb) {
662 bool alt = t->rb & RB_ALT;
663 s = "RB";
664 if (rb == RB_CVT_V2)
665 s += std::string("v2") + (alt ? ",video-optimized" : "");
666 else if (rb == RB_CVT_V3)
667 s += std::string("v3") + (alt ? ",h-blank-160" : "");
668 }
669 add_str(s, flags);
670 if (t->hsize_mm || t->vsize_mm)
671 add_str(s, std::to_string(t->hsize_mm) + " mm x " + std::to_string(t->vsize_mm) + " mm");
672 if (t->hsize_mm > dtd_max_hsize_mm)
673 dtd_max_hsize_mm = t->hsize_mm;
674 if (t->vsize_mm > dtd_max_vsize_mm)
675 dtd_max_vsize_mm = t->vsize_mm;
676 if (!s.empty())
677 s = " (" + s + ")";
678 unsigned pixclk_khz = t->pixclk_khz / (t->ycbcr420 ? 2 : 1);
679
680 char buf[10];
681
682 sprintf(buf, "%u%s", t->vact, t->interlaced ? "i" : "");
683 printf("%s%s: %5ux%-5s %10.6f Hz %3u:%-3u %8.3f kHz %13.6f MHz%s\n",
684 prefix, type,
685 t->hact, buf,
686 refresh,
687 t->hratio, t->vratio,
688 out_hor_freq_khz,
689 pixclk / 1000000.0,
690 s.c_str());
691
692 unsigned len = strlen(prefix) + 2;
693
694 if (!t->ycbcr420 && detailed && options[OptXModeLineTimings])
695 print_modeline(len, t, refresh);
696 else if (!t->ycbcr420 && detailed && options[OptFBModeTimings])
697 print_fbmode(len, t, refresh, hor_freq_khz);
698 else if (!t->ycbcr420 && detailed && options[OptV4L2Timings])
699 print_v4l2_timing(t, refresh, type);
700 else if (detailed)
701 print_detailed_timing(len + strlen(type) + 6, t);
702
703 if (!do_checks)
704 return ok;
705
706 if (!memcmp(type, "DTD", 3)) {
707 unsigned vic, dmt;
708 const timings *vic_t = cta_close_match_to_vic(*t, vic);
709
710 // We report this even if there is no CTA block since it
711 // is still likely that the actual VIC timings were intended.
712 if (vic_t)
713 warn("DTD is similar but not identical to VIC %u.\n", vic);
714
715 if (cta_matches_vic(*t, vic) && has_cta &&
716 !cta.preparsed_has_vic[0][vic]) {
717 warn("DTD is identical to VIC %u, which is not present in the CTA Ext Block.\n", vic);
718
719 if (cta.preparsed_max_vic_pixclk_khz && t->pixclk_khz > 340000 &&
720 t->pixclk_khz > cta.preparsed_max_vic_pixclk_khz)
721 cta.warn_about_hdmi_2x_dtd = true;
722 }
723
724 const timings *dmt_t = close_match_to_dmt(*t, dmt);
725 if (!vic_t && dmt_t)
726 warn("DTD is similar but not identical to DMT 0x%02x.\n", dmt);
727 }
728
729 if (refresh) {
730 min_vert_freq_hz = min(min_vert_freq_hz, refresh);
731 max_vert_freq_hz = max(max_vert_freq_hz, refresh);
732 }
733 if (hor_freq_khz) {
734 min_hor_freq_hz = min(min_hor_freq_hz, hor_freq_khz * 1000.0);
735 max_hor_freq_hz = max(max_hor_freq_hz, hor_freq_khz * 1000.0);
736 max_pixclk_khz = max(max_pixclk_khz, pixclk_khz);
737 if (t->pos_pol_hsync && !t->pos_pol_vsync && t->vsync == 3)
738 base.max_pos_neg_hor_freq_khz = hor_freq_khz;
739 }
740
741 if (t->ycbcr420 && t->pixclk_khz < 590000)
742 warn_once("Some YCbCr 4:2:0 timings are invalid for HDMI 2.1 (which requires an RGB timings pixel rate >= 590 MHz).\n");
743 if (t->hfp <= 0)
744 fail("0 or negative horizontal front porch.\n");
745 if (t->hbp <= 0)
746 fail("0 or negative horizontal back porch.\n");
747 if (t->vbp <= 0)
748 fail("0 or negative vertical back porch.\n");
749 if (!base.max_display_width_mm && !base.max_display_height_mm) {
750 /* this is valid */
751 } else if (!t->hsize_mm && !t->vsize_mm) {
752 /* this is valid */
753 } else if (cta.preparsed_image_size == hdmi_image_size_ratio) {
754 /* this is valid */
755 } else if (t->hsize_mm > base.max_display_width_mm + 9 ||
756 t->vsize_mm > base.max_display_height_mm + 9) {
757 fail("Mismatch of image size %ux%u mm vs display size %ux%u mm.\n",
758 t->hsize_mm, t->vsize_mm, base.max_display_width_mm, base.max_display_height_mm);
759 } else if (t->hsize_mm < base.max_display_width_mm - 9 &&
760 t->vsize_mm < base.max_display_height_mm - 9) {
761 fail("Mismatch of image size %ux%u mm vs display size %ux%u mm.\n",
762 t->hsize_mm, t->vsize_mm, base.max_display_width_mm, base.max_display_height_mm);
763 }
764 if (t->hsize_mm && t->vsize_mm) {
765 if (t->hsize_mm < 100 || t->vsize_mm < 100) {
766 warn("Dubious image size (%ux%u mm is smaller than 100x100 mm).\n",
767 t->hsize_mm, t->vsize_mm);
768 } else if (t->hratio && t->vratio) {
769 unsigned vsize = (t->hsize_mm * t->vratio) / t->hratio;
770
771 if (vsize < t->vsize_mm - 10 || vsize > t->vsize_mm + 10)
772 warn("Image size is %dx%d mm, but based on the picture AR it should be %dx%d mm.\n",
773 t->hsize_mm, t->vsize_mm, t->hsize_mm, vsize);
774 }
775 }
776 return ok;
777 }
778
779 std::string containerid2s(const unsigned char *x)
780 {
781 char buf[40];
782
783 sprintf(buf, "%02x%02x%02x%02x-%02x%02x-%02x%02x-%02x%02x-%02x%02x%02x%02x%02x%02x",
784 x[0], x[1], x[2], x[3],
785 x[4], x[5],
786 x[6], x[7],
787 x[8], x[9],
788 x[10], x[11], x[12], x[13], x[14], x[15]);
789 return buf;
790 }
791
792 std::string utohex(unsigned char x)
793 {
794 char buf[10];
795
796 sprintf(buf, "0x%02hhx", x);
797 return buf;
798 }
799
800 const char *oui_name(unsigned oui, unsigned *ouinum)
801 {
802 unsigned ouinumscratch;
803 if (!ouinum) ouinum = &ouinumscratch;
804 const char *name;
805 switch (oui) {
806 #define oneoui(c,k,n) case c: *ouinum = kOUI_##k; name = n; break;
807 #include "oui.h"
808 default: *ouinum = 0; name = NULL; break;
809 }
810 return name;
811 }
812
813 void edid_state::data_block_oui(std::string block_name, const unsigned char *x,
814 unsigned length, unsigned *ouinum, bool ignorezeros, bool do_ascii, bool big_endian,
815 bool silent)
816 {
817 std::string buf;
818 char ascii[4];
819 unsigned oui;
820 const char *ouiname = NULL;
821 bool matched_reverse = false;
822 bool matched_ascii = false;
823 bool valid_ascii = false;
824
825 if (big_endian)
826 oui = ((length > 0 ? x[0] : 0) << 16) + ((length > 1 ? x[1] : 0) << 8) + (length > 2 ? x[2] : 0);
827 else
828 oui = ((length > 2 ? x[2] : 0) << 16) + ((length > 1 ? x[1] : 0) << 8) + (length > 0 ? x[0] : 0);
829
830 buf = ouitohex(oui);
831 if (length < 3) {
832 sprintf(ascii, "?"); // some characters are null
833 if (ouinum) *ouinum = 0; // doesn't match a known OUI
834 } else {
835 valid_ascii = (x[0] >= 'A' && x[1] >= 'A' && x[2] >= 'A' && x[0] <= 'Z' && x[1] <= 'Z' && x[2] <= 'Z');
836 sprintf(ascii, "%c%c%c", x[0], x[1], x[2]);
837
838 ouiname = oui_name(oui, ouinum);
839 if (!ouiname) {
840 big_endian = !big_endian;
841 unsigned reversedoui = ((oui & 0xff) << 16) + (oui & 0x00ff00) + (oui >> 16);
842 ouiname = oui_name(reversedoui, ouinum);
843 if (ouiname) {
844 oui = reversedoui;
845 buf = ouitohex(oui);
846 matched_reverse = true;
847 } else if (do_ascii && valid_ascii) {
848 unsigned asciioui = (x[0] << 24) + (x[1] << 16) + (x[2] << 8);
849 ouiname = oui_name(asciioui, ouinum);
850 if (ouiname) {
851 matched_ascii = true;
852 }
853 }
854 }
855 }
856
857 std::string name;
858 if (ouiname) {
859 if (matched_ascii)
860 name = block_name + " (" + ouiname + ")" + ", PNP ID '" + ascii + "'";
861 else
862 name = block_name + " (" + ouiname + ")" + ", OUI " + buf;
863 } else if (do_ascii && valid_ascii) {
864 name = block_name + ", PNP ID '" + ascii + "'";
865 } else {
866 name = block_name + ", OUI " + buf;
867 }
868 // assign string to data_block before outputting errors
869 data_block = name;
870
871 if (oui || !ignorezeros) {
872 if (!silent)
873 printf(" %s:\n", data_block.c_str());
874 if (length < 3) {
875 fail("Data block length (%d) is not enough to contain an OUI.\n", length);
876 } else if (ouiname) {
877 if (do_ascii && !valid_ascii)
878 warn("Expected PNP ID but found OUI.\n");
879 if (matched_reverse)
880 fail("Endian-ness (%s) of OUI is different than expected (%s).\n", big_endian ? "be" : "le", big_endian ? "le" : "be");
881 } else if (!do_ascii && valid_ascii) {
882 warn("Unknown OUI %s (possible PNP %s).\n", buf.c_str(), ascii);
883 } else if (!do_ascii) {
884 warn("Unknown OUI %s.\n", buf.c_str());
885 }
886 }
887 }
888
889 std::string ouitohex(unsigned oui)
890 {
891 char buf[32];
892
893 sprintf(buf, "%02X-%02X-%02X", (oui >> 16) & 0xff, (oui >> 8) & 0xff, oui & 0xff);
894 return buf;
895 }
896
897 bool memchk(const unsigned char *x, unsigned len, unsigned char v)
898 {
899 for (unsigned i = 0; i < len; i++)
900 if (x[i] != v)
901 return false;
902 return true;
903 }
904
905 void hex_block(const char *prefix, const unsigned char *x,
906 unsigned length, bool show_ascii, unsigned step)
907 {
908 unsigned i, j;
909
910 for (i = 0; i < length; i += step) {
911 unsigned len = min(step, length - i);
912
913 printf("%s", prefix);
914 for (j = 0; j < len; j++)
915 printf("%s%02x", j ? " " : "", x[i + j]);
916
917 if (show_ascii) {
918 for (j = len; j < step; j++)
919 printf(" ");
920 printf(" '");
921 for (j = 0; j < len; j++)
922 printf("%c", x[i + j] >= ' ' && x[i + j] <= '~' ? x[i + j] : '.');
923 printf("'");
924 }
925 printf("\n");
926 }
927 }
928
929 static bool edid_add_byte(const char *s, bool two_digits = true)
930 {
931 char buf[3];
932
933 if (state.edid_size == sizeof(edid))
934 return false;
935 buf[0] = s[0];
936 buf[1] = two_digits ? s[1] : 0;
937 buf[2] = 0;
938 edid[state.edid_size++] = strtoul(buf, NULL, 16);
939 return true;
940 }
941
942 static bool extract_edid_quantumdata(const char *start)
943 {
944 /* Parse QuantumData 980 EDID files */
945 do {
946 start = strstr(start, ">");
947 if (!start)
948 return false;
949 start++;
950 for (unsigned i = 0; start[i] && start[i + 1] && i < 256; i += 2)
951 if (!edid_add_byte(start + i))
952 return false;
953 start = strstr(start, "<BLOCK");
954 } while (start);
955 return state.edid_size;
956 }
957
958 static const char *ignore_chars = ",:;";
959
960 static bool extract_edid_hex(const char *s, bool require_two_digits = true)
961 {
962 for (; *s; s++) {
963 if (isspace(*s) || strchr(ignore_chars, *s))
964 continue;
965
966 if (*s == '0' && tolower(s[1]) == 'x') {
967 s++;
968 continue;
969 }
970
971 /* Read one or two hex digits from the log */
972 if (!isxdigit(s[0])) {
973 if (state.edid_size && state.edid_size % 128 == 0)
974 break;
975 return false;
976 }
977 if (require_two_digits && !isxdigit(s[1])) {
978 odd_hex_digits = true;
979 return false;
980 }
981 if (!edid_add_byte(s, isxdigit(s[1])))
982 return false;
983 if (isxdigit(s[1]))
984 s++;
985 }
986 return state.edid_size;
987 }
988
989 static bool extract_edid_xrandr(const char *start)
990 {
991 static const char indentation1[] = " ";
992 static const char indentation2[] = "\t\t";
993 /* Used to detect that we've gone past the EDID property */
994 static const char half_indentation1[] = " ";
995 static const char half_indentation2[] = "\t";
996 const char *indentation;
997 const char *s;
998
999 for (;;) {
1000 unsigned j;
1001
1002 /* Get the next start of the line of EDID hex, assuming spaces for indentation */
1003 s = strstr(start, indentation = indentation1);
1004 /* Did we skip the start of another property? */
1005 if (s && s > strstr(start, half_indentation1))
1006 break;
1007
1008 /* If we failed, retry assuming tabs for indentation */
1009 if (!s) {
1010 s = strstr(start, indentation = indentation2);
1011 /* Did we skip the start of another property? */
1012 if (s && s > strstr(start, half_indentation2))
1013 break;
1014 }
1015
1016 if (!s)
1017 break;
1018
1019 start = s + strlen(indentation);
1020
1021 for (j = 0; j < 16; j++, start += 2) {
1022 /* Read a %02x from the log */
1023 if (!isxdigit(start[0]) || !isxdigit(start[1])) {
1024 if (j)
1025 break;
1026 return false;
1027 }
1028 if (!edid_add_byte(start))
1029 return false;
1030 }
1031 }
1032 return state.edid_size;
1033 }
1034
1035 static bool extract_edid_xorg(const char *start)
1036 {
1037 bool find_first_num = true;
1038
1039 for (; *start; start++) {
1040 if (find_first_num) {
1041 const char *s;
1042
1043 /* skip ahead to the : */
1044 s = strstr(start, ": \t");
1045 if (!s)
1046 s = strstr(start, ": ");
1047 if (!s)
1048 break;
1049 start = s;
1050 /* and find the first number */
1051 while (!isxdigit(start[1]))
1052 start++;
1053 find_first_num = false;
1054 continue;
1055 } else {
1056 /* Read a %02x from the log */
1057 if (!isxdigit(*start)) {
1058 find_first_num = true;
1059 continue;
1060 }
1061 if (!edid_add_byte(start))
1062 return false;
1063 start++;
1064 }
1065 }
1066 return state.edid_size;
1067 }
1068
1069 static bool extract_edid(int fd, FILE *error)
1070 {
1071 std::vector<char> edid_data;
1072 char buf[EDID_PAGE_SIZE];
1073
1074 for (;;) {
1075 ssize_t i = read(fd, buf, sizeof(buf));
1076
1077 if (i < 0)
1078 return false;
1079 if (i == 0)
1080 break;
1081 edid_data.insert(edid_data.end(), buf, buf + i);
1082 }
1083
1084 if (edid_data.empty()) {
1085 state.edid_size = 0;
1086 return false;
1087 }
1088 // Ensure it is safely terminated by a 0 char
1089 edid_data.push_back('\0');
1090
1091 const char *data = &edid_data[0];
1092 const char *start;
1093
1094 /* Look for edid-decode output */
1095 start = strstr(data, "edid-decode (hex):");
1096 if (!start)
1097 start = strstr(data, "EDID (hex):");
1098 if (start) {
1099 bool ok = extract_edid_hex(strchr(start, ':'));
1100 float diag;
1101
1102 if (state.diagonal)
1103 return ok;
1104
1105 start = strstr(start, "Diagonal: ");
1106 if (start)
1107 start = strchr(start, ' ') + 1;
1108 if (ok && start && sscanf(start, "%f\"", &diag) == 1) {
1109 state.diagonal = diag;
1110 }
1111 return ok;
1112 }
1113
1114 /* Look for C-array */
1115 start = strstr(data, "unsigned char edid[] = {");
1116 if (start)
1117 return extract_edid_hex(strchr(start, '{') + 1, false);
1118
1119 /* Look for QuantumData EDID output */
1120 start = strstr(data, "<BLOCK");
1121 if (start)
1122 return extract_edid_quantumdata(start);
1123
1124 /* Look for xrandr --verbose output (lines of 16 hex bytes) */
1125 start = strstr(data, "EDID_DATA:");
1126 if (!start)
1127 start = strstr(data, "EDID:");
1128 if (start)
1129 return extract_edid_xrandr(start);
1130
1131 /* Look for an EDID in an Xorg.0.log file */
1132 start = strstr(data, "EDID (in hex):");
1133 if (start)
1134 start = strstr(start, "(II)");
1135 if (start)
1136 return extract_edid_xorg(start);
1137
1138 unsigned i;
1139
1140 /* Is the EDID provided in hex? */
1141 for (i = 0; i < 32 && i < edid_data.size() &&
1142 (isspace(data[i]) || strchr(ignore_chars, data[i]) ||
1143 tolower(data[i]) == 'x' || isxdigit(data[i])); i++);
1144
1145 if (i == 32)
1146 return extract_edid_hex(data);
1147
1148 // Drop the extra '\0' byte since we now assume binary data
1149 edid_data.pop_back();
1150
1151 /* Assume binary */
1152 if (edid_data.size() > sizeof(edid)) {
1153 if (!options[OptPhysicalAddress])
1154 fprintf(error, "Binary EDID length %zu is greater than %zu.\n",
1155 edid_data.size(), sizeof(edid));
1156 return false;
1157 }
1158 memcpy(edid, data, edid_data.size());
1159 state.edid_size = edid_data.size();
1160 return true;
1161 }
1162
1163 static int edid_from_file(const char *from_file, FILE *error)
1164 {
1165 #ifdef O_BINARY
1166 // Windows compatibility
1167 int flags = O_RDONLY | O_BINARY;
1168 #else
1169 int flags = O_RDONLY;
1170 #endif
1171 int fd;
1172
1173 if (!strcmp(from_file, "-")) {
1174 from_file = "stdin";
1175 fd = 0;
1176 } else if ((fd = open(from_file, flags)) == -1) {
1177 perror(from_file);
1178 std::exit(EXIT_FAILURE);
1179 }
1180
1181 odd_hex_digits = false;
1182 if (!extract_edid(fd, error)) {
1183 if (options[OptPhysicalAddress])
1184 return -1;
1185 if (!state.edid_size) {
1186 fprintf(error, "EDID of '%s' was empty.\n", from_file);
1187 return -1;
1188 }
1189 fprintf(error, "EDID extract of '%s' failed: ", from_file);
1190 if (odd_hex_digits)
1191 fprintf(error, "odd number of hexadecimal digits.\n");
1192 else
1193 fprintf(error, "unknown format.\n");
1194 return -1;
1195 }
1196 if (state.edid_size % EDID_PAGE_SIZE) {
1197 if (!options[OptPhysicalAddress])
1198 fprintf(error, "EDID length %u is not a multiple of %u.\n",
1199 state.edid_size, EDID_PAGE_SIZE);
1200 return -1;
1201 }
1202 state.num_blocks = state.edid_size / EDID_PAGE_SIZE;
1203 if (fd != 0)
1204 close(fd);
1205
1206 if (memcmp(edid, "\x00\xFF\xFF\xFF\xFF\xFF\xFF\x00", 8)) {
1207 if (!options[OptPhysicalAddress])
1208 fprintf(error, "No EDID header found in '%s'.\n", from_file);
1209 return -1;
1210 }
1211 return 0;
1212 }
1213
1214 /* generic extension code */
1215
1216 std::string block_name(unsigned char block)
1217 {
1218 char buf[10];
1219
1220 switch (block) {
1221 case 0x00: return "Base EDID";
1222 case 0x02: return "CTA-861 Extension Block";
1223 case 0x10: return "Video Timing Extension Block";
1224 case 0x20: return "EDID 2.0 Extension Block";
1225 case 0x40: return "Display Information Extension Block";
1226 case 0x50: return "Localized String Extension Block";
1227 case 0x60: return "Microdisplay Interface Extension Block";
1228 case 0x70: return "DisplayID Extension Block";
1229 case 0xf0: return "Block Map Extension Block";
1230 case 0xff: return "Manufacturer-Specific Extension Block";
1231 default:
1232 sprintf(buf, " 0x%02x", block);
1233 return std::string("Unknown EDID Extension Block") + buf;
1234 }
1235 }
1236
1237 void edid_state::parse_block_map(const unsigned char *x)
1238 {
1239 unsigned last_valid_block_tag = 0;
1240 bool fail_once = false;
1241 unsigned offset = 1;
1242 unsigned i;
1243
1244 if (block_nr == 1)
1245 block_map.saw_block_1 = true;
1246 else if (!block_map.saw_block_1)
1247 fail("No EDID Block Map Extension found in block 1.\n");
1248 else if (block_nr == 128)
1249 block_map.saw_block_128 = true;
1250
1251 if (block_nr > 1)
1252 offset = 128;
1253
1254 for (i = 1; i < 127; i++) {
1255 unsigned block = offset + i;
1256
1257 if (x[i]) {
1258 last_valid_block_tag++;
1259 if (i != last_valid_block_tag && !fail_once) {
1260 fail("Valid block tags are not consecutive.\n");
1261 fail_once = true;
1262 }
1263 printf(" Block %3u: %s\n", block, block_name(x[i]).c_str());
1264 if (block >= num_blocks) {
1265 if (!fail_once)
1266 fail("Invalid block number %u.\n", block);
1267 fail_once = true;
1268 } else if (x[i] != edid[block * EDID_PAGE_SIZE]) {
1269 fail("Block %u tag mismatch: expected 0x%02x, but got 0x%02x.\n",
1270 block, edid[block * EDID_PAGE_SIZE], x[i]);
1271 }
1272 } else if (block < num_blocks) {
1273 fail("Block %u tag mismatch: expected 0x%02x, but got 0x00.\n",
1274 block, edid[block * EDID_PAGE_SIZE]);
1275 }
1276 }
1277 }
1278
1279 void edid_state::preparse_extension(unsigned char *x)
1280 {
1281 switch (x[0]) {
1282 case 0x02:
1283 has_cta = true;
1284 preparse_cta_block(x);
1285 break;
1286 case 0x50:
1287 preparse_ls_ext_block(x);
1288 break;
1289 case 0x70:
1290 has_dispid = true;
1291 preparse_displayid_block(x);
1292 break;
1293 }
1294 }
1295
1296 void edid_state::parse_extension(const unsigned char *x)
1297 {
1298 block = block_name(x[0]);
1299 data_block.clear();
1300 unused_bytes = 0;
1301
1302 printf("\n");
1303 if (block_nr && x[0] == 0)
1304 block = "Unknown EDID Extension Block 0x00";
1305 printf("Block %u, %s:\n", block_nr, block.c_str());
1306
1307 switch (x[0]) {
1308 case 0x02:
1309 parse_cta_block(x);
1310 break;
1311 case 0x10:
1312 parse_vtb_ext_block(x);
1313 break;
1314 case 0x20:
1315 fail("Deprecated extension block for EDID 2.0, do not use.\n");
1316 break;
1317 case 0x40:
1318 parse_di_ext_block(x);
1319 break;
1320 case 0x50:
1321 parse_ls_ext_block(x);
1322 break;
1323 case 0x70:
1324 parse_displayid_block(x);
1325 break;
1326 case 0xf0:
1327 parse_block_map(x);
1328 if (block_nr != 1 && block_nr != 128)
1329 fail("Must be used in block 1 and 128.\n");
1330 break;
1331 default:
1332 hex_block(" ", x, EDID_PAGE_SIZE);
1333 fail("Unknown Extension Block.\n");
1334 break;
1335 }
1336
1337 data_block.clear();
1338 do_checksum("", x, EDID_PAGE_SIZE, EDID_PAGE_SIZE - 1, unused_bytes);
1339 }
1340
1341 void edid_state::print_preferred_timings()
1342 {
1343 if (base.preferred_timing.is_valid()) {
1344 printf("\n----------------\n");
1345 printf("\nPreferred Video Timing if only Block 0 is parsed:\n");
1346 print_timings(" ", base.preferred_timing, true, false);
1347 }
1348
1349 if (!cta.preferred_timings.empty()) {
1350 printf("\n----------------\n");
1351 printf("\nPreferred Video Timing%s if Block 0 and CTA-861 Blocks are parsed:\n",
1352 cta.preferred_timings.size() > 1 ? "s" : "");
1353 for (vec_timings_ext::iterator iter = cta.preferred_timings.begin();
1354 iter != cta.preferred_timings.end(); ++iter)
1355 print_timings(" ", *iter, true, false);
1356 }
1357
1358 if (!cta.preferred_timings_vfpdb.empty()) {
1359 printf("\n----------------\n");
1360 printf("\nPreferred Video Timing%s if Block 0 and CTA-861 Blocks are parsed with VFPDB support:\n",
1361 cta.preferred_timings_vfpdb.size() > 1 ? "s" : "");
1362 for (vec_timings_ext::iterator iter = cta.preferred_timings_vfpdb.begin();
1363 iter != cta.preferred_timings_vfpdb.end(); ++iter)
1364 print_timings(" ", *iter, true, false);
1365 }
1366
1367 if (!dispid.preferred_timings.empty()) {
1368 printf("\n----------------\n");
1369 printf("\nPreferred Video Timing%s if Block 0 and DisplayID Blocks are parsed:\n",
1370 dispid.preferred_timings.size() > 1 ? "s" : "");
1371 for (vec_timings_ext::iterator iter = dispid.preferred_timings.begin();
1372 iter != dispid.preferred_timings.end(); ++iter)
1373 print_timings(" ", *iter, true, false);
1374 }
1375 }
1376
1377 void edid_state::print_native_res()
1378 {
1379 typedef std::pair<unsigned, unsigned> resolution;
1380 typedef std::set<resolution> resolution_set;
1381 resolution_set native_prog, native_int, native_nvrdb;
1382 unsigned native_width = 0, native_height = 0;
1383 unsigned native_width_int = 0, native_height_int = 0;
1384
1385 // Note: it is also a mismatch if Block 0 does not define a
1386 // native resolution, but other blocks do.
1387 bool native_mismatch = false;
1388 bool native_int_mismatch = false;
1389
1390 if (base.preferred_timing.is_valid() && base.preferred_is_also_native) {
1391 if (base.preferred_timing.t.interlaced) {
1392 native_width_int = base.preferred_timing.t.hact;
1393 native_height_int = base.preferred_timing.t.vact;
1394 } else {
1395 native_width = base.preferred_timing.t.hact;
1396 native_height = base.preferred_timing.t.vact;
1397 }
1398 }
1399
1400 if (!native_width && dispid.native_width) {
1401 native_width = dispid.native_width;
1402 native_height = dispid.native_height;
1403 native_mismatch = true;
1404 } else if (dispid.native_width && native_width &&
1405 (dispid.native_width != native_width ||
1406 dispid.native_height != native_height)) {
1407 native_mismatch = true;
1408 }
1409
1410 for (vec_timings_ext::iterator iter = cta.native_timings.begin();
1411 iter != cta.native_timings.end(); ++iter) {
1412 if (iter->t.interlaced) {
1413 native_int.insert(std::pair<unsigned, unsigned>(iter->t.hact, iter->t.vact));
1414 if (!native_width_int) {
1415 native_width_int = iter->t.hact;
1416 native_height_int = iter->t.vact;
1417 native_int_mismatch = true;
1418 } else if (native_width_int &&
1419 (iter->t.hact != native_width_int ||
1420 iter->t.vact != native_height_int)) {
1421 native_int_mismatch = true;
1422 }
1423 } else {
1424 native_prog.insert(std::pair<unsigned, unsigned>(iter->t.hact, iter->t.vact));
1425 if (!native_width) {
1426 native_width = iter->t.hact;
1427 native_height = iter->t.vact;
1428 native_mismatch = true;
1429 } else if (native_width &&
1430 (iter->t.hact != native_width ||
1431 iter->t.vact != native_height)) {
1432 native_mismatch = true;
1433 }
1434 }
1435 }
1436
1437 for (vec_timings_ext::iterator iter = cta.native_timing_nvrdb.begin();
1438 iter != cta.native_timing_nvrdb.end(); ++iter) {
1439 if (iter->t.interlaced) {
1440 fail("Interlaced native timing in NVRDB.\n");
1441 } else {
1442 native_nvrdb.insert(std::pair<unsigned, unsigned>(iter->t.hact, iter->t.vact));
1443 if (!native_width) {
1444 native_width = iter->t.hact;
1445 native_height = iter->t.vact;
1446 native_mismatch = true;
1447 } else if (native_width &&
1448 (iter->t.hact != native_width ||
1449 iter->t.vact != native_height)) {
1450 if (iter->t.hact >= 4096 || iter->t.vact >= 4096) {
1451 native_width = iter->t.hact;
1452 native_height = iter->t.vact;
1453 }
1454 native_mismatch = true;
1455 }
1456 }
1457 }
1458
1459 if (diagonal) {
1460 if (image_width) {
1461 double w = image_width;
1462 double h = image_height;
1463 double d = sqrt(w * w + h * h) / 254.0;
1464
1465 if (fabs(diagonal - d) >= 0.1) {
1466 warn("Specified diagonal is %.1f\", calculated diagonal is %.1f\" for EDID image size %.1fx%.1fmm.\n",
1467 diagonal, d, w / 10.0, h / 10.0);
1468 }
1469 }
1470 if (native_width) {
1471 double w = native_width;
1472 double h = native_height;
1473 double d = diagonal * 254.0;
1474 double c = sqrt((d * d) / (w * w + h * h));
1475
1476 w *= c;
1477 h *= c;
1478
1479 if (image_width) {
1480 printf("\n----------------\n");
1481 printf("\nCalculated image size for a diagonal of %.1f\" is %.1fx%.1fmm (native resolution %ux%u).\n",
1482 diagonal, w / 10.0, h / 10.0, native_width, native_height);
1483
1484 if (fabs((double)image_width - w) >= 100.0 ||
1485 fabs((double)image_height - h) >= 100.0)
1486 warn("Calculated image size is %.1fx%.1fmm, EDID image size is %.1fx%.1fmm.\n",
1487 w / 10.0, h / 10.0,
1488 image_width / 10.0, image_height / 10.0);
1489 } else {
1490 warn("No image size was specified, but it is calculated as %.1fx%.1fmm.\n",
1491 w / 10.0, h / 10.0);
1492 }
1493 if (has_cta && !cta.nvrdb_has_size && (w > 25500 || h > 25500))
1494 warn("Calculated image width or height > 255 cm, recommend including an NVRDB with image size.\n");
1495 }
1496 }
1497
1498 if (!base.is_analog && native_width == 0 && native_width_int == 0) {
1499 warn("No Native Video Resolution was defined.\n");
1500 // See also section 7.2.2 in the CTA-861-I (or later) standard:
1501 if (has_cta)
1502 warn(" Hint: set 'Native detailed modes' to a non-0 value, or add a Native Video Resolution Data Block.\n");
1503 }
1504
1505 if (!options[OptNativeResolution])
1506 return;
1507
1508 if (native_width == 0 && native_width_int == 0) {
1509 printf("\n----------------\n");
1510 printf("\nNo Native Video Resolution was defined.\n");
1511 return;
1512 }
1513
1514 if ((native_width || native_width_int) &&
1515 !native_mismatch && !native_int_mismatch) {
1516 printf("\n----------------\n");
1517 printf("\nNative Video Resolution%s:\n",
1518 native_width && native_width_int ? "s" : "");
1519 if (native_width)
1520 printf(" %ux%u\n", native_width, native_height);
1521 if (native_width_int)
1522 printf(" %ux%ui\n", native_width_int, native_height_int);
1523 return;
1524 }
1525
1526 if (base.preferred_timing.is_valid() && base.preferred_is_also_native) {
1527 printf("\n----------------\n");
1528 printf("\nNative Video Resolution if only Block 0 is parsed:\n");
1529 printf(" %ux%u%s\n",
1530 base.preferred_timing.t.hact, base.preferred_timing.t.vact,
1531 base.preferred_timing.t.interlaced ? "i" : "");
1532 }
1533
1534 if (!cta.native_timings.empty()) {
1535 printf("\n----------------\n");
1536 printf("\nNative Video Resolution%s if Block 0 and CTA-861 Blocks are parsed:\n",
1537 native_prog.size() + native_int.size() > 1 ? "s" : "");
1538 for (resolution_set::iterator iter = native_prog.begin();
1539 iter != native_prog.end(); ++iter)
1540 printf(" %ux%u\n", iter->first, iter->second);
1541 for (resolution_set::iterator iter = native_int.begin();
1542 iter != native_int.end(); ++iter)
1543 printf(" %ux%ui\n", iter->first, iter->second);
1544 }
1545
1546 if (!cta.native_timing_nvrdb.empty()) {
1547 printf("\n----------------\n");
1548 printf("\nNative Video Resolution if Block 0 and CTA-861 Blocks are parsed with NVRDB support:\n");
1549 for (resolution_set::iterator iter = native_nvrdb.begin();
1550 iter != native_nvrdb.end(); ++iter)
1551 printf(" %ux%u\n", iter->first, iter->second);
1552 }
1553
1554 if (dispid.native_width) {
1555 printf("\n----------------\n");
1556 printf("\nNative Video Resolution if the DisplayID Blocks are parsed:\n");
1557 printf(" %ux%u\n", dispid.native_width, dispid.native_height);
1558 }
1559 }
1560
1561 int edid_state::parse_edid()
1562 {
1563 hide_serial_numbers = options[OptHideSerialNumbers];
1564 replace_unique_ids = options[OptReplaceUniqueIDs];
1565
1566 to_utf8 = options[OptUTF8];
1567
1568 preparse_base_block(edid);
1569 if (replace_unique_ids)
1570 replace_checksum(edid, EDID_PAGE_SIZE);
1571
1572 for (unsigned i = 1; i < num_blocks; i++)
1573 preparse_extension(edid + i * EDID_PAGE_SIZE);
1574
1575 if (options[OptPhysicalAddress]) {
1576 printf("%x.%x.%x.%x\n",
1577 (cta.preparsed_phys_addr >> 12) & 0xf,
1578 (cta.preparsed_phys_addr >> 8) & 0xf,
1579 (cta.preparsed_phys_addr >> 4) & 0xf,
1580 cta.preparsed_phys_addr & 0xf);
1581 return 0;
1582 }
1583
1584 if (!options[OptSkipHexDump]) {
1585 printf("edid-decode (hex):\n\n");
1586 for (unsigned i = 0; i < num_blocks; i++) {
1587 hex_block("", edid + i * EDID_PAGE_SIZE, EDID_PAGE_SIZE, false);
1588 if (i == num_blocks - 1 && options[OptOnlyHexDump])
1589 return 0;
1590 printf("\n");
1591 }
1592 printf("----------------\n\n");
1593 if (diagonal) {
1594 printf("Diagonal: %.1f\"\n\n", diagonal);
1595 printf("----------------\n\n");
1596 }
1597 }
1598
1599 block = block_name(0x00);
1600 printf("Block %u, %s:\n", block_nr, block.c_str());
1601 parse_base_block(edid);
1602
1603 for (unsigned i = 1; i < num_blocks; i++) {
1604 block_nr++;
1605 printf("\n----------------\n");
1606 parse_extension(edid + i * EDID_PAGE_SIZE);
1607 }
1608
1609 block = "";
1610 block_nr = EDID_MAX_BLOCKS;
1611
1612 if (cta.has_svrs)
1613 cta_resolve_svrs();
1614
1615 if (options[OptPreferredTimings])
1616 print_preferred_timings();
1617
1618 print_native_res();
1619
1620 if (!options[OptCheck] && !options[OptCheckInline])
1621 return 0;
1622
1623 check_base_block(edid);
1624 if (has_cta)
1625 check_cta_blocks();
1626 if (has_dispid)
1627 check_displayid_blocks();
1628
1629 printf("\n----------------\n");
1630
1631 if (!options[OptSkipSHA] && strlen(STRING(SHA))) {
1632 options[OptSkipSHA] = 1;
1633 printf("\n");
1634 print_version();
1635 }
1636
1637 if (options[OptCheck]) {
1638 if (warnings)
1639 show_msgs(true);
1640 if (failures)
1641 show_msgs(false);
1642 }
1643 printf("\nEDID conformity: %s\n", failures ? "FAIL" : "PASS");
1644 return failures ? -2 : 0;
1645 }
1646
1647 /* InfoFrame parsing */
1648
1649 static unsigned char infoframe[32];
1650 static unsigned if_size;
1651
1652 static unsigned char eld[128];
1653 static unsigned eld_size;
1654
1655 static bool if_add_byte(const char *s)
1656 {
1657 char buf[3];
1658
1659 if (if_size == sizeof(infoframe))
1660 return false;
1661 buf[0] = s[0];
1662 buf[1] = s[1];
1663 buf[2] = 0;
1664 infoframe[if_size++] = strtoul(buf, NULL, 16);
1665 return true;
1666 }
1667
1668 static bool extract_if_hex(const char *s)
1669 {
1670 for (; *s; s++) {
1671 if (isspace(*s) || strchr(ignore_chars, *s))
1672 continue;
1673
1674 /* Read one or two hex digits from the log */
1675 if (!isxdigit(s[0]))
1676 break;
1677
1678 if (!isxdigit(s[1])) {
1679 odd_hex_digits = true;
1680 return false;
1681 }
1682 if (!if_add_byte(s))
1683 return false;
1684 s++;
1685 }
1686 return if_size;
1687 }
1688
1689 static bool extract_if(int fd)
1690 {
1691 std::vector<char> if_data;
1692 char buf[128];
1693
1694 for (;;) {
1695 ssize_t i = read(fd, buf, sizeof(buf));
1696
1697 if (i < 0)
1698 return false;
1699 if (i == 0)
1700 break;
1701 if_data.insert(if_data.end(), buf, buf + i);
1702 }
1703
1704 if (if_data.empty()) {
1705 if_size = 0;
1706 return false;
1707 }
1708 // Ensure it is safely terminated by a 0 char
1709 if_data.push_back('\0');
1710
1711 const char *data = &if_data[0];
1712 const char *start;
1713
1714 /* Look for edid-decode output */
1715 start = strstr(data, "edid-decode InfoFrame (hex):");
1716 if (start)
1717 return extract_if_hex(strchr(start, ':') + 1);
1718
1719 unsigned i;
1720
1721 for (i = 0; i < 32 && (isspace(data[i]) || strchr(ignore_chars, data[i]) ||
1722 tolower(data[i]) == 'x' || isxdigit(data[i])); i++);
1723
1724 if (i == 32)
1725 return extract_if_hex(data);
1726
1727 // Drop the extra '\0' byte since we now assume binary data
1728 if_data.pop_back();
1729
1730 if_size = if_data.size();
1731
1732 /* Assume binary */
1733 if (if_size > sizeof(infoframe)) {
1734 fprintf(stderr, "Binary InfoFrame length %u is greater than %zu.\n",
1735 if_size, sizeof(infoframe));
1736 return false;
1737 }
1738 memcpy(infoframe, data, if_size);
1739 return true;
1740 }
1741
1742 static int if_from_file(const char *from_file)
1743 {
1744 #ifdef O_BINARY
1745 // Windows compatibility
1746 int flags = O_RDONLY | O_BINARY;
1747 #else
1748 int flags = O_RDONLY;
1749 #endif
1750 int fd;
1751
1752 memset(infoframe, 0, sizeof(infoframe));
1753 if_size = 0;
1754
1755 if (!strcmp(from_file, "-")) {
1756 from_file = "stdin";
1757 fd = 0;
1758 } else if ((fd = open(from_file, flags)) == -1) {
1759 perror(from_file);
1760 return -1;
1761 }
1762
1763 odd_hex_digits = false;
1764 if (!extract_if(fd)) {
1765 if (!if_size) {
1766 fprintf(stderr, "InfoFrame of '%s' was empty.\n", from_file);
1767 return -1;
1768 }
1769 fprintf(stderr, "InfoFrame extraction of '%s' failed: ", from_file);
1770 if (odd_hex_digits)
1771 fprintf(stderr, "odd number of hexadecimal digits.\n");
1772 else
1773 fprintf(stderr, "unknown format.\n");
1774 return -1;
1775 }
1776 close(fd);
1777
1778 return 0;
1779 }
1780
1781 static void show_if_msgs(bool is_warn)
1782 {
1783 printf("\n%s:\n\n", is_warn ? "Warnings" : "Failures");
1784 if (s_msgs[0][is_warn].empty())
1785 return;
1786 printf("InfoFrame:\n%s",
1787 s_msgs[0][is_warn].c_str());
1788 }
1789
1790 static bool eld_add_byte(const char *s)
1791 {
1792 char buf[3];
1793
1794 if (eld_size == sizeof(eld))
1795 return false;
1796 buf[0] = s[0];
1797 buf[1] = s[1];
1798 buf[2] = 0;
1799 eld[eld_size++] = strtoul(buf, NULL, 16);
1800 return true;
1801 }
1802
1803 static bool extract_eld_hex(const char *s)
1804 {
1805 for (; *s; s++) {
1806 if (isspace(*s) || strchr(ignore_chars, *s))
1807 continue;
1808
1809 if (*s == '0' && tolower(s[1]) == 'x') {
1810 s++;
1811 continue;
1812 }
1813
1814 /* Read one or two hex digits from the log */
1815 if (!isxdigit(s[0]))
1816 break;
1817
1818 if (!isxdigit(s[1])) {
1819 odd_hex_digits = true;
1820 return false;
1821 }
1822 if (!eld_add_byte(s))
1823 return false;
1824 s++;
1825 }
1826 return eld_size;
1827 }
1828
1829 static bool extract_eld(int fd)
1830 {
1831 std::vector<char> eld_data;
1832 char buf[128];
1833
1834 for (;;) {
1835 ssize_t i = read(fd, buf, sizeof(buf));
1836
1837 if (i < 0)
1838 return false;
1839 if (i == 0)
1840 break;
1841 eld_data.insert(eld_data.end(), buf, buf + i);
1842 }
1843
1844 if (eld_data.empty()) {
1845 eld_size = 0;
1846 return false;
1847 }
1848 // Ensure it is safely terminated by a 0 char
1849 eld_data.push_back('\0');
1850
1851 const char *data = &eld_data[0];
1852 const char *start;
1853
1854 /* Look for edid-decode output */
1855 start = strstr(data, "edid-decode ELD (hex):");
1856 if (start)
1857 return extract_eld_hex(strchr(start, ':') + 1);
1858
1859 unsigned i;
1860
1861 /* Is the EDID provided in hex? */
1862 for (i = 0; i < 32 && (isspace(data[i]) || strchr(ignore_chars, data[i]) ||
1863 tolower(data[i]) == 'x' || isxdigit(data[i])); i++);
1864
1865 if (i == 32)
1866 return extract_eld_hex(data);
1867
1868 // Drop the extra '\0' byte since we now assume binary data
1869 eld_data.pop_back();
1870
1871 eld_size = eld_data.size();
1872
1873 /* Assume binary */
1874 if (eld_size > sizeof(eld)) {
1875 fprintf(stderr, "Binary ELD length %u is greater than %zu.\n",
1876 eld_size, sizeof(eld));
1877 return false;
1878 }
1879 memcpy(eld, data, eld_size);
1880 return true;
1881 }
1882
1883 static int eld_from_file(const char *from_file)
1884 {
1885 #ifdef O_BINARY
1886 // Windows compatibility
1887 int flags = O_RDONLY | O_BINARY;
1888 #else
1889 int flags = O_RDONLY;
1890 #endif
1891 int fd;
1892
1893 memset(eld, 0, sizeof(eld));
1894 eld_size = 0;
1895
1896 if (!strcmp(from_file, "-")) {
1897 from_file = "stdin";
1898 fd = 0;
1899 } else if ((fd = open(from_file, flags)) == -1) {
1900 perror(from_file);
1901 return -1;
1902 }
1903
1904 odd_hex_digits = false;
1905 if (!extract_eld(fd)) {
1906 if (!eld_size) {
1907 fprintf(stderr, "ELD of '%s' was empty.\n", from_file);
1908 return -1;
1909 }
1910 fprintf(stderr, "ELD extraction of '%s' failed: ", from_file);
1911 if (odd_hex_digits)
1912 fprintf(stderr, "odd number of hexadecimal digits.\n");
1913 else
1914 fprintf(stderr, "unknown format.\n");
1915 return -1;
1916 }
1917 close(fd);
1918
1919 return 0;
1920 }
1921
1922 static void show_eld_msgs(bool is_warn)
1923 {
1924 printf("\n%s:\n\n", is_warn ? "Warnings" : "Failures");
1925 if (s_msgs[0][is_warn].empty())
1926 return;
1927 printf("ELD:\n%s",
1928 s_msgs[0][is_warn].c_str());
1929 }
1930
1931 int edid_state::parse_eld(const std::string &fname)
1932 {
1933 int ret = eld_from_file(fname.c_str());
1934 unsigned int min_size = 4;
1935 unsigned baseline_size;
1936 unsigned char ver;
1937
1938 if (ret)
1939 return ret;
1940
1941 if (!options[OptSkipHexDump]) {
1942 printf("edid-decode ELD (hex):\n\n");
1943 hex_block("", eld, eld_size, false);
1944 if (options[OptOnlyHexDump])
1945 return 0;
1946 printf("\n----------------\n\n");
1947 }
1948
1949 if (eld_size < min_size) {
1950 fail("ELD is too small to parse.\n");
1951 return -1;
1952 }
1953
1954 ver = eld[0] >> 3;
1955 switch (ver) {
1956 case 1:
1957 warn("Obsolete Baseline ELD version (%d)\n", ver);
1958 break;
1959 case 2:
1960 printf("Baseline ELD version: 861.D or below\n");
1961 break;
1962 default:
1963 warn("Unsupported ELD version (%d)\n", ver);
1964 break;
1965 }
1966
1967 baseline_size = eld[2] * 4;
1968 if (baseline_size > 80)
1969 warn("ELD too big\n");
1970
1971 parse_eld_baseline(&eld[4], baseline_size);
1972
1973 if (!options[OptCheck] && !options[OptCheckInline])
1974 return 0;
1975
1976 printf("\n----------------\n");
1977
1978 if (!options[OptSkipSHA] && strlen(STRING(SHA))) {
1979 options[OptSkipSHA] = 1;
1980 printf("\n");
1981 print_version();
1982 }
1983
1984 if (options[OptCheck]) {
1985 if (warnings)
1986 show_eld_msgs(true);
1987 if (failures)
1988 show_eld_msgs(false);
1989 }
1990
1991 printf("\n%s conformity: %s\n",
1992 state.data_block.empty() ? "ELD" : state.data_block.c_str(),
1993 failures ? "FAIL" : "PASS");
1994 return failures ? -2 : 0;
1995 }
1996 int edid_state::parse_if(const std::string &fname)
1997 {
1998 int ret = if_from_file(fname.c_str());
1999 unsigned min_size = 4;
2000 bool is_hdmi = false;
2001
2002 if (ret)
2003 return ret;
2004
2005 state.block_nr = 0;
2006 state.data_block.clear();
2007
2008 if (!options[OptSkipHexDump]) {
2009 printf("edid-decode InfoFrame (hex):\n\n");
2010 hex_block("", infoframe, if_size, false);
2011 if (options[OptOnlyHexDump])
2012 return 0;
2013 printf("\n----------------\n\n");
2014 }
2015
2016 if (infoframe[0] >= 0x80) {
2017 is_hdmi = true;
2018 min_size++;
2019 }
2020
2021 if (if_size < min_size) {
2022 fail("InfoFrame is too small to parse.\n");
2023 return -1;
2024 }
2025
2026 if (is_hdmi) {
2027 do_checksum("HDMI InfoFrame ", infoframe, if_size, 3);
2028 printf("\n");
2029 memcpy(infoframe + 3, infoframe + 4, if_size - 4);
2030 infoframe[0] &= 0x7f;
2031 if_size--;
2032 }
2033
2034 switch (infoframe[0]) {
2035 case 0x01:
2036 parse_if_vendor(infoframe, if_size);
2037 break;
2038 case 0x02:
2039 parse_if_avi(infoframe, if_size);
2040 break;
2041 case 0x03:
2042 parse_if_spd(infoframe, if_size);
2043 break;
2044 case 0x04:
2045 parse_if_audio(infoframe, if_size);
2046 break;
2047 case 0x05:
2048 parse_if_mpeg_source(infoframe, if_size);
2049 break;
2050 case 0x06:
2051 parse_if_ntsc_vbi(infoframe, if_size);
2052 break;
2053 case 0x07:
2054 parse_if_drm(infoframe, if_size);
2055 break;
2056 default:
2057 if (infoframe[0] <= 0x1f)
2058 fail("Reserved InfoFrame type %hhx.\n", infoframe[0]);
2059 else
2060 fail("Forbidden InfoFrame type %hhx.\n", infoframe[0]);
2061 break;
2062 }
2063
2064 if (!options[OptCheck] && !options[OptCheckInline])
2065 return 0;
2066
2067 printf("\n----------------\n");
2068
2069 if (!options[OptSkipSHA] && strlen(STRING(SHA))) {
2070 options[OptSkipSHA] = 1;
2071 printf("\n");
2072 print_version();
2073 }
2074
2075 if (options[OptCheck]) {
2076 if (warnings)
2077 show_if_msgs(true);
2078 if (failures)
2079 show_if_msgs(false);
2080 }
2081
2082 printf("\n%s conformity: %s\n",
2083 state.data_block.empty() ? "InfoFrame" : state.data_block.c_str(),
2084 failures ? "FAIL" : "PASS");
2085 return failures ? -2 : 0;
2086 }
2087
2088 #ifndef __EMSCRIPTEN__
2089
2090 static unsigned char crc_calc(const unsigned char *b)
2091 {
2092 unsigned char sum = 0;
2093 unsigned i;
2094
2095 for (i = 0; i < 127; i++)
2096 sum += b[i];
2097 return 256 - sum;
2098 }
2099
2100 static int crc_ok(const unsigned char *b)
2101 {
2102 return crc_calc(b) == b[127];
2103 }
2104
2105 static void hexdumpedid(FILE *f, const unsigned char *edid, unsigned size)
2106 {
2107 unsigned b, i, j;
2108
2109 for (b = 0; b < size / 128; b++) {
2110 const unsigned char *buf = edid + 128 * b;
2111
2112 if (b)
2113 fprintf(f, "\n");
2114 for (i = 0; i < 128; i += 0x10) {
2115 fprintf(f, "%02x", buf[i]);
2116 for (j = 1; j < 0x10; j++) {
2117 fprintf(f, " %02x", buf[i + j]);
2118 }
2119 fprintf(f, "\n");
2120 }
2121 if (!crc_ok(buf))
2122 fprintf(f, "Block %u has a checksum error (should be 0x%02x).\n",
2123 b, crc_calc(buf));
2124 }
2125 }
2126
2127 static void carraydumpedid(FILE *f, const unsigned char *edid, unsigned size)
2128 {
2129 unsigned b, i, j;
2130
2131 fprintf(f, "const unsigned char edid[] = {\n");
2132 for (b = 0; b < size / 128; b++) {
2133 const unsigned char *buf = edid + 128 * b;
2134
2135 if (b)
2136 fprintf(f, "\n");
2137 for (i = 0; i < 128; i += 8) {
2138 fprintf(f, "\t0x%02x,", buf[i]);
2139 for (j = 1; j < 8; j++) {
2140 fprintf(f, " 0x%02x,", buf[i + j]);
2141 }
2142 fprintf(f, "\n");
2143 }
2144 if (!crc_ok(buf))
2145 fprintf(f, "\t/* Block %u has a checksum error (should be 0x%02x). */\n",
2146 b, crc_calc(buf));
2147 }
2148 fprintf(f, "};\n");
2149 }
2150
2151 // This format can be read by the QuantumData EDID editor
2152 static void xmldumpedid(FILE *f, const unsigned char *edid, unsigned size)
2153 {
2154 fprintf(f, "<?xml version=\"1.0\" encoding=\"UTF-8\" standalone=\"no\"?>\n");
2155 fprintf(f, "<DATAOBJ>\n");
2156 fprintf(f, " <HEADER TYPE=\"DID\" VERSION=\"1.0\"/>\n");
2157 fprintf(f, " <DATA>\n");
2158 for (unsigned b = 0; b < size / 128; b++) {
2159 const unsigned char *buf = edid + 128 * b;
2160
2161 fprintf(f, " <BLOCK%u>", b);
2162 for (unsigned i = 0; i < 128; i++)
2163 fprintf(f, "%02X", buf[i]);
2164 fprintf(f, "</BLOCK%u>\n", b);
2165 }
2166 fprintf(f, " </DATA>\n");
2167 fprintf(f, "</DATAOBJ>\n");
2168 }
2169
2170 static int edid_to_file(const char *to_file, enum output_format out_fmt)
2171 {
2172 FILE *out;
2173
2174 if (!strcmp(to_file, "-")) {
2175 to_file = "stdout";
2176 out = stdout;
2177 } else if ((out = fopen(to_file, "w")) == NULL) {
2178 perror(to_file);
2179 return -1;
2180 }
2181 if (out_fmt == OUT_FMT_DEFAULT)
2182 out_fmt = out == stdout ? OUT_FMT_HEX : OUT_FMT_RAW;
2183
2184 switch (out_fmt) {
2185 default:
2186 case OUT_FMT_HEX:
2187 hexdumpedid(out, edid, state.edid_size);
2188 break;
2189 case OUT_FMT_RAW:
2190 fwrite(edid, state.edid_size, 1, out);
2191 break;
2192 case OUT_FMT_CARRAY:
2193 carraydumpedid(out, edid, state.edid_size);
2194 break;
2195 case OUT_FMT_XML:
2196 xmldumpedid(out, edid, state.edid_size);
2197 break;
2198 }
2199
2200 if (out != stdout)
2201 fclose(out);
2202 return 0;
2203 }
2204
2205 enum cvt_opts {
2206 CVT_WIDTH = 0,
2207 CVT_HEIGHT,
2208 CVT_FPS,
2209 CVT_INTERLACED,
2210 CVT_OVERSCAN,
2211 CVT_RB,
2212 CVT_ALT,
2213 CVT_RB_H_BLANK,
2214 CVT_RB_V_BLANK,
2215 CVT_EARLY_VSYNC,
2216 };
2217
2218 static int parse_cvt_subopt(char **subopt_str, double *value)
2219 {
2220 int opt;
2221 char *opt_str;
2222
2223 static const char * const subopt_list[] = {
2224 "w",
2225 "h",
2226 "fps",
2227 "interlaced",
2228 "overscan",
2229 "rb",
2230 "alt",
2231 "hblank",
2232 "vblank",
2233 "early-vsync",
2234 nullptr
2235 };
2236
2237 opt = getsubopt(subopt_str, (char * const *)subopt_list, &opt_str);
2238
2239 if (opt_str == nullptr && opt != CVT_INTERLACED && opt != CVT_ALT &&
2240 opt != CVT_OVERSCAN && opt != CVT_EARLY_VSYNC) {
2241 fprintf(stderr, "No value given to suboption <%s>.\n",
2242 subopt_list[opt]);
2243 usage();
2244 std::exit(EXIT_FAILURE);
2245 }
2246
2247 if (opt_str)
2248 *value = strtod(opt_str, nullptr);
2249 else
2250 *value = 0;
2251 return opt;
2252 }
2253
2254 static void parse_cvt(char *optarg)
2255 {
2256 unsigned w = 0, h = 0;
2257 double fps = 0;
2258 unsigned rb = RB_NONE;
2259 unsigned rb_h_blank = 0;
2260 unsigned rb_v_blank = 460;
2261 bool interlaced = false;
2262 bool alt = false;
2263 bool overscan = false;
2264 bool early_vsync = false;
2265
2266 while (*optarg != '\0') {
2267 int opt;
2268 double opt_val;
2269
2270 opt = parse_cvt_subopt(&optarg, &opt_val);
2271
2272 switch (opt) {
2273 case CVT_WIDTH:
2274 w = round(opt_val);
2275 break;
2276 case CVT_HEIGHT:
2277 h = round(opt_val);
2278 break;
2279 case CVT_FPS:
2280 fps = opt_val;
2281 break;
2282 case CVT_RB:
2283 rb = opt_val;
2284 break;
2285 case CVT_OVERSCAN:
2286 overscan = true;
2287 break;
2288 case CVT_INTERLACED:
2289 interlaced = opt_val;
2290 break;
2291 case CVT_ALT:
2292 alt = opt_val;
2293 break;
2294 case CVT_RB_H_BLANK:
2295 rb_h_blank = opt_val;
2296 break;
2297 case CVT_RB_V_BLANK:
2298 rb_v_blank = opt_val;
2299 if (rb_v_blank < 460) {
2300 fprintf(stderr, "vblank must be >= 460, set to 460.\n");
2301 rb_v_blank = 460;
2302 } else if (rb_v_blank > 705) {
2303 fprintf(stderr, "warning: vblank values > 705 might not be supported by RBv3 compliant sources.\n");
2304 }
2305 break;
2306 case CVT_EARLY_VSYNC:
2307 early_vsync = true;
2308 break;
2309 default:
2310 break;
2311 }
2312 }
2313
2314 if (!w || !h || !fps) {
2315 fprintf(stderr, "Missing width, height and/or fps.\n");
2316 usage();
2317 std::exit(EXIT_FAILURE);
2318 }
2319 if (interlaced)
2320 fps /= 2;
2321 timings t = state.calc_cvt_mode(w, h, fps, rb, interlaced, overscan, alt,
2322 rb_h_blank, rb_v_blank, early_vsync);
2323 state.print_timings("", &t, "CVT", "", true, false);
2324 }
2325
2326 struct gtf_parsed_data {
2327 unsigned w, h;
2328 double freq;
2329 double C, M, K, J;
2330 bool overscan;
2331 bool interlaced;
2332 bool secondary;
2333 bool params_from_edid;
2334 enum gtf_ip_parm ip_parm;
2335 };
2336
2337 enum gtf_opts {
2338 GTF_WIDTH = 0,
2339 GTF_HEIGHT,
2340 GTF_FPS,
2341 GTF_HORFREQ,
2342 GTF_PIXCLK,
2343 GTF_INTERLACED,
2344 GTF_OVERSCAN,
2345 GTF_SECONDARY,
2346 GTF_C2,
2347 GTF_M,
2348 GTF_K,
2349 GTF_J2,
2350 };
2351
2352 static int parse_gtf_subopt(char **subopt_str, double *value)
2353 {
2354 int opt;
2355 char *opt_str;
2356
2357 static const char * const subopt_list[] = {
2358 "w",
2359 "h",
2360 "fps",
2361 "horfreq",
2362 "pixclk",
2363 "interlaced",
2364 "overscan",
2365 "secondary",
2366 "C",
2367 "M",
2368 "K",
2369 "J",
2370 nullptr
2371 };
2372
2373 opt = getsubopt(subopt_str, (char * const *)subopt_list, &opt_str);
2374
2375 if (opt == -1) {
2376 fprintf(stderr, "Invalid suboptions specified.\n");
2377 usage();
2378 std::exit(EXIT_FAILURE);
2379 }
2380 if (opt_str == nullptr && opt != GTF_INTERLACED && opt != GTF_OVERSCAN &&
2381 opt != GTF_SECONDARY) {
2382 fprintf(stderr, "No value given to suboption <%s>.\n",
2383 subopt_list[opt]);
2384 usage();
2385 std::exit(EXIT_FAILURE);
2386 }
2387
2388 if (opt == GTF_C2 || opt == GTF_J2)
2389 *value = round(2.0 * strtod(opt_str, nullptr));
2390 else if (opt_str)
2391 *value = strtod(opt_str, nullptr);
2392 else
2393 *value = 0;
2394 return opt;
2395 }
2396
2397 static void parse_gtf(char *optarg, gtf_parsed_data &data)
2398 {
2399 memset(&data, 0, sizeof(data));
2400 data.params_from_edid = true;
2401 data.C = 40;
2402 data.M = 600;
2403 data.K = 128;
2404 data.J = 20;
2405
2406 while (*optarg != '\0') {
2407 int opt;
2408 double opt_val;
2409
2410 opt = parse_gtf_subopt(&optarg, &opt_val);
2411
2412 switch (opt) {
2413 case GTF_WIDTH:
2414 data.w = round(opt_val);
2415 break;
2416 case GTF_HEIGHT:
2417 data.h = round(opt_val);
2418 break;
2419 case GTF_FPS:
2420 data.freq = opt_val;
2421 data.ip_parm = gtf_ip_vert_freq;
2422 break;
2423 case GTF_HORFREQ:
2424 data.freq = opt_val;
2425 data.ip_parm = gtf_ip_hor_freq;
2426 break;
2427 case GTF_PIXCLK:
2428 data.freq = opt_val;
2429 data.ip_parm = gtf_ip_clk_freq;
2430 break;
2431 case GTF_INTERLACED:
2432 data.interlaced = true;
2433 break;
2434 case GTF_OVERSCAN:
2435 data.overscan = true;
2436 break;
2437 case GTF_SECONDARY:
2438 data.secondary = true;
2439 break;
2440 case GTF_C2:
2441 data.C = opt_val / 2.0;
2442 data.params_from_edid = false;
2443 break;
2444 case GTF_M:
2445 data.M = round(opt_val);
2446 data.params_from_edid = false;
2447 break;
2448 case GTF_K:
2449 data.K = round(opt_val);
2450 data.params_from_edid = false;
2451 break;
2452 case GTF_J2:
2453 data.J = opt_val / 2.0;
2454 data.params_from_edid = false;
2455 break;
2456 default:
2457 break;
2458 }
2459 }
2460
2461 if (!data.w || !data.h) {
2462 fprintf(stderr, "Missing width and/or height.\n");
2463 usage();
2464 std::exit(EXIT_FAILURE);
2465 }
2466 if (!data.freq) {
2467 fprintf(stderr, "One of fps, horfreq or pixclk must be given.\n");
2468 usage();
2469 std::exit(EXIT_FAILURE);
2470 }
2471 if (!data.secondary)
2472 data.params_from_edid = false;
2473 if (data.interlaced && data.ip_parm == gtf_ip_vert_freq)
2474 data.freq /= 2;
2475 }
2476
2477 static void show_gtf(gtf_parsed_data &data)
2478 {
2479 timings t;
2480
2481 t = state.calc_gtf_mode(data.w, data.h, data.freq, data.interlaced,
2482 data.ip_parm, data.overscan, data.secondary,
2483 data.C, data.M, data.K, data.J);
2484 calc_ratio(&t);
2485 state.print_timings("", &t, "GTF", "", true, false);
2486 }
2487
2488 enum ovt_opts {
2489 OVT_RID,
2490 OVT_WIDTH,
2491 OVT_HEIGHT,
2492 OVT_FPS,
2493 };
2494
2495 static int parse_ovt_subopt(char **subopt_str, unsigned *value)
2496 {
2497 int opt;
2498 char *opt_str;
2499
2500 static const char * const subopt_list[] = {
2501 "rid",
2502 "w",
2503 "h",
2504 "fps",
2505 nullptr
2506 };
2507
2508 opt = getsubopt(subopt_str, (char* const*) subopt_list, &opt_str);
2509
2510 if (opt == -1) {
2511 fprintf(stderr, "Invalid suboptions specified.\n");
2512 usage();
2513 std::exit(EXIT_FAILURE);
2514 }
2515 if (opt_str == nullptr) {
2516 fprintf(stderr, "No value given to suboption <%s>.\n",
2517 subopt_list[opt]);
2518 usage();
2519 std::exit(EXIT_FAILURE);
2520 }
2521
2522 if (opt_str)
2523 *value = strtoul(opt_str, NULL, 0);
2524 return opt;
2525 }
2526
2527 static void parse_ovt(char *optarg)
2528 {
2529 unsigned rid = 0;
2530 unsigned w = 0, h = 0;
2531 unsigned fps = 0;
2532
2533 while (*optarg != '\0') {
2534 int opt;
2535 unsigned opt_val;
2536
2537 opt = parse_ovt_subopt(&optarg, &opt_val);
2538
2539 switch (opt) {
2540 case OVT_RID:
2541 rid = opt_val;
2542 break;
2543 case OVT_WIDTH:
2544 w = opt_val;
2545 break;
2546 case OVT_HEIGHT:
2547 h = opt_val;
2548 break;
2549 case OVT_FPS:
2550 fps = opt_val;
2551 break;
2552 default:
2553 break;
2554 }
2555 }
2556
2557 if ((!rid && (!w || !h)) || !fps) {
2558 fprintf(stderr, "Missing rid, width, height and/or fps.\n");
2559 usage();
2560 std::exit(EXIT_FAILURE);
2561 }
2562 unsigned hratio = 0, vratio = 0;
2563 if (rid) {
2564 const cta_rid *r = find_rid(rid);
2565
2566 if (r) {
2567 w = r->hact;
2568 h = r->vact;
2569 hratio = r->hratio;
2570 vratio = r->vratio;
2571 }
2572 }
2573 timings t = state.calc_ovt_mode(w, h, hratio, vratio, fps);
2574 state.print_timings("", &t, "OVT", "", true, false);
2575 }
2576
2577 enum test_reliability_opts {
2578 REL_DURATION,
2579 REL_MSLEEP,
2580 };
2581
2582 static int parse_test_reliability_subopt(char **subopt_str, unsigned *value)
2583 {
2584 int opt;
2585 char *opt_str;
2586
2587 static const char * const subopt_list[] = {
2588 "duration",
2589 "msleep",
2590 nullptr
2591 };
2592
2593 opt = getsubopt(subopt_str, (char* const*) subopt_list, &opt_str);
2594
2595 if (opt == -1) {
2596 fprintf(stderr, "Invalid suboptions specified.\n");
2597 usage();
2598 std::exit(EXIT_FAILURE);
2599 }
2600 if (opt_str == nullptr) {
2601 fprintf(stderr, "No value given to suboption <%s>.\n",
2602 subopt_list[opt]);
2603 usage();
2604 std::exit(EXIT_FAILURE);
2605 }
2606
2607 if (opt_str)
2608 *value = strtoul(opt_str, NULL, 0);
2609 return opt;
2610 }
2611
2612 static void parse_test_reliability(char *optarg, unsigned &duration, unsigned &msleep)
2613 {
2614 while (*optarg != '\0') {
2615 int opt;
2616 unsigned opt_val;
2617
2618 opt = parse_test_reliability_subopt(&optarg, &opt_val);
2619
2620 switch (opt) {
2621 case REL_DURATION:
2622 duration = opt_val;
2623 break;
2624 case REL_MSLEEP:
2625 msleep = opt_val;
2626 break;
2627 default:
2628 break;
2629 }
2630 }
2631 }
2632
2633 int main(int argc, char **argv)
2634 {
2635 char short_options[26 * 2 * 3 + 1];
2636 enum output_format out_fmt = OUT_FMT_DEFAULT;
2637 gtf_parsed_data gtf_data;
2638 unsigned list_rid = 0;
2639 int adapter_fd = -1;
2640 double hdcp_ri_sleep = 0;
2641 std::vector<std::string> if_names;
2642 std::vector<std::string> eld_names;
2643 unsigned test_rel_duration = 0;
2644 unsigned test_rel_msleep = 50;
2645 unsigned idx = 0;
2646 unsigned i;
2647 int ret = 0;
2648
2649 for (i = 0; long_options[i].name; i++) {
2650 if (!isalpha(long_options[i].val))
2651 continue;
2652 short_options[idx++] = long_options[i].val;
2653 if (long_options[i].has_arg == required_argument) {
2654 short_options[idx++] = ':';
2655 } else if (long_options[i].has_arg == optional_argument) {
2656 short_options[idx++] = ':';
2657 short_options[idx++] = ':';
2658 }
2659 }
2660 while (true) {
2661 int option_index = 0;
2662 unsigned val;
2663 const timings *t;
2664 char buf[16];
2665 int ch;
2666
2667 short_options[idx] = 0;
2668 ch = getopt_long(argc, argv, short_options,
2669 long_options, &option_index);
2670 if (ch == -1)
2671 break;
2672
2673 options[ch] = 1;
2674
2675 if (!option_index) {
2676 for (i = 0; long_options[i].val; i++) {
2677 if (long_options[i].val == ch) {
2678 option_index = i;
2679 break;
2680 }
2681 }
2682 }
2683 if (long_options[option_index].has_arg == optional_argument &&
2684 !optarg && argv[optind] && argv[optind][0] != '-')
2685 optarg = argv[optind++];
2686
2687 switch (ch) {
2688 case OptHelp:
2689 usage();
2690 return -1;
2691 case OptOutputFormat:
2692 if (!strcmp(optarg, "hex")) {
2693 out_fmt = OUT_FMT_HEX;
2694 } else if (!strcmp(optarg, "raw")) {
2695 out_fmt = OUT_FMT_RAW;
2696 } else if (!strcmp(optarg, "carray")) {
2697 out_fmt = OUT_FMT_CARRAY;
2698 } else if (!strcmp(optarg, "xml")) {
2699 out_fmt = OUT_FMT_XML;
2700 } else {
2701 usage();
2702 std::exit(EXIT_FAILURE);
2703 }
2704 break;
2705 case OptDiag: {
2706 double diag;
2707
2708 diag = strtod(optarg, NULL);
2709 if (isnormal(diag)) {
2710 if (diag == 0 || (diag >= 10 && diag <= 2559))
2711 state.diagonal = diag;
2712 else
2713 fprintf(stderr, "Ignored diagonal, expected to be between 10 and 2559 inches.\n");
2714 }
2715 break;
2716 }
2717 #ifdef __HAS_I2C_DEV__
2718 case OptI2CAdapter: {
2719 std::string device = optarg;
2720
2721 if (device[0] >= '0' && device[0] <= '9' && device.length() <= 3) {
2722 static char newdev[20];
2723
2724 sprintf(newdev, "/dev/i2c-%s", optarg);
2725 device = newdev;
2726 }
2727
2728 adapter_fd = request_i2c_adapter(device.c_str());
2729 if (adapter_fd < 0)
2730 std::exit(EXIT_FAILURE);
2731 break;
2732 }
2733 case OptI2CTestReliability:
2734 if (optarg)
2735 parse_test_reliability(optarg, test_rel_duration, test_rel_msleep);
2736 break;
2737 #endif
2738 case OptI2CHDCPRi:
2739 hdcp_ri_sleep = strtod(optarg, NULL);
2740 break;
2741 case OptSTD: {
2742 unsigned char byte1, byte2 = 0;
2743 char *endptr;
2744
2745 byte1 = strtoul(optarg, &endptr, 0);
2746 if (*endptr == ',')
2747 byte2 = strtoul(endptr + 1, NULL, 0);
2748 state.print_standard_timing("", byte1, byte2, false, true);
2749 break;
2750 }
2751 case OptDMT:
2752 val = strtoul(optarg, NULL, 0);
2753 t = find_dmt_id(val);
2754 if (t) {
2755 sprintf(buf, "DMT 0x%02x", val);
2756 state.print_timings("", t, buf, "", true, false);
2757 } else {
2758 fprintf(stderr, "Unknown DMT code 0x%02x.\n", val);
2759 }
2760 break;
2761 case OptVIC:
2762 val = strtoul(optarg, NULL, 0);
2763 t = find_vic_id(val);
2764 if (t) {
2765 sprintf(buf, "VIC %3u", val);
2766 state.print_timings("", t, buf, "", true, false);
2767 } else {
2768 fprintf(stderr, "Unknown VIC code %u.\n", val);
2769 }
2770 break;
2771 case OptHDMIVIC:
2772 val = strtoul(optarg, NULL, 0);
2773 t = find_hdmi_vic_id(val);
2774 if (t) {
2775 sprintf(buf, "HDMI VIC %u", val);
2776 state.print_timings("", t, buf, "", true, false);
2777 } else {
2778 fprintf(stderr, "Unknown HDMI VIC code %u.\n", val);
2779 }
2780 break;
2781 case OptCVT:
2782 parse_cvt(optarg);
2783 break;
2784 case OptGTF:
2785 parse_gtf(optarg, gtf_data);
2786 break;
2787 case OptOVT:
2788 parse_ovt(optarg);
2789 break;
2790 case OptListRIDTimings:
2791 list_rid = strtoul(optarg, NULL, 0);
2792 break;
2793 case OptInfoFrame:
2794 if_names.push_back(optarg);
2795 break;
2796 case OptEld:
2797 eld_names.push_back(optarg);
2798 break;
2799 case ':':
2800 fprintf(stderr, "Option '%s' requires a value.\n",
2801 argv[optind]);
2802 usage();
2803 return -1;
2804 case '?':
2805 fprintf(stderr, "Unknown argument '%s'.\n",
2806 argv[optind]);
2807 usage();
2808 return -1;
2809 }
2810 }
2811 if (optind == argc && options[OptVersion]) {
2812 print_version();
2813 return 0;
2814 }
2815
2816 if (options[OptListEstTimings])
2817 state.list_established_timings();
2818 if (options[OptListDMTs])
2819 state.list_dmts();
2820 if (options[OptListVICs])
2821 state.cta_list_vics();
2822 if (options[OptListHDMIVICs])
2823 state.cta_list_hdmi_vics();
2824 if (options[OptListRIDs])
2825 state.cta_list_rids();
2826 if (options[OptListRIDTimings])
2827 state.cta_list_rid_timings(list_rid);
2828
2829 if (options[OptListEstTimings] || options[OptListDMTs] ||
2830 options[OptListVICs] || options[OptListHDMIVICs] ||
2831 options[OptListRIDs] || options[OptListRIDTimings])
2832 return 0;
2833
2834 if (options[OptCVT] || options[OptDMT] || options[OptVIC] ||
2835 options[OptHDMIVIC] || options[OptSTD] || options[OptOVT])
2836 return 0;
2837
2838 if (options[OptGTF] && (!gtf_data.params_from_edid || optind == argc)) {
2839 show_gtf(gtf_data);
2840 return 0;
2841 }
2842
2843 if (optind == argc) {
2844 if (adapter_fd >= 0 && options[OptI2CEDID]) {
2845 ret = read_edid(adapter_fd, edid, options[OptPhysicalAddress]);
2846 if (ret > 0) {
2847 state.edid_size = ret * EDID_PAGE_SIZE;
2848 state.num_blocks = ret;
2849 ret = 0;
2850 }
2851 } else if (adapter_fd >= 0) {
2852 if (options[OptI2CHDCP])
2853 ret = read_hdcp(adapter_fd);
2854 if (options[OptI2CHDCPRi])
2855 ret = read_hdcp_ri(adapter_fd, hdcp_ri_sleep);
2856 if (options[OptI2CTestReliability])
2857 ret = test_reliability(adapter_fd, test_rel_duration, test_rel_msleep);
2858 } else if ((options[OptInfoFrame] || options[OptEld]) && !options[OptGTF]) {
2859 ret = 0;
2860 } else {
2861 ret = edid_from_file("-", stdout);
2862 }
2863 } else {
2864 ret = edid_from_file(argv[optind], argv[optind + 1] ? stderr : stdout);
2865 }
2866
2867 if (ret && options[OptPhysicalAddress]) {
2868 printf("f.f.f.f\n");
2869 return 0;
2870 }
2871 if (optind < argc - 1)
2872 return ret ? ret : edid_to_file(argv[optind + 1], out_fmt);
2873
2874 if (options[OptGTF]) {
2875 timings t;
2876
2877 state.preparse_base_block(edid);
2878
2879 t = state.calc_gtf_mode(gtf_data.w, gtf_data.h, gtf_data.freq,
2880 gtf_data.interlaced, gtf_data.ip_parm,
2881 gtf_data.overscan);
2882 unsigned hbl = t.hfp + t.hsync + t.hbp;
2883 unsigned htotal = t.hact + hbl;
2884 double hor_freq_khz = htotal ? (double)t.pixclk_khz / htotal : 0;
2885
2886 if (state.base.supports_sec_gtf &&
2887 hor_freq_khz >= state.base.sec_gtf_start_freq) {
2888 t = state.calc_gtf_mode(gtf_data.w, gtf_data.h, gtf_data.freq,
2889 gtf_data.interlaced, gtf_data.ip_parm,
2890 gtf_data.overscan, true,
2891 state.base.C, state.base.M,
2892 state.base.K, state.base.J);
2893 }
2894 calc_ratio(&t);
2895 if (t.hfp <= 0)
2896 state.print_timings("", &t, "GTF", "INVALID: Hfront <= 0", true, false);
2897 else
2898 state.print_timings("", &t, "GTF", "", true, false);
2899 return 0;
2900 }
2901
2902 if (!ret && state.edid_size)
2903 ret = state.parse_edid();
2904
2905 bool show_line = state.edid_size;
2906
2907 for (const auto &n : if_names) {
2908 if (show_line)
2909 printf("\n================\n\n");
2910 show_line = true;
2911
2912 state.warnings = state.failures = 0;
2913 for (unsigned i = 0; i < EDID_MAX_BLOCKS + 1; i++) {
2914 s_msgs[i][0].clear();
2915 s_msgs[i][1].clear();
2916 }
2917 int r = state.parse_if(n);
2918 if (r && !ret)
2919 ret = r;
2920 }
2921
2922 for (const auto &n : eld_names) {
2923 if (show_line)
2924 printf("\n================\n\n");
2925 show_line = true;
2926
2927 state.warnings = state.failures = 0;
2928 for (unsigned i = 0; i < EDID_MAX_BLOCKS + 1; i++) {
2929 s_msgs[i][0].clear();
2930 s_msgs[i][1].clear();
2931 }
2932 int r = state.parse_eld(n);
2933 if (r && !ret)
2934 ret = r;
2935 }
2936 return ret;
2937 }
2938
2939 #else
2940
2941 /*
2942 * The surrounding JavaScript implementation will call this function
2943 * each time it wants to decode an EDID. So this should reset all the
2944 * state and start over.
2945 */
2946 extern "C" int parse_edid(const char *input, float diag)
2947 {
2948 for (unsigned i = 0; i < EDID_MAX_BLOCKS + 1; i++) {
2949 s_msgs[i][0].clear();
2950 s_msgs[i][1].clear();
2951 }
2952 options[OptCheck] = 1;
2953 options[OptPreferredTimings] = 1;
2954 options[OptNativeResolution] = 1;
2955 options[OptSkipSHA] = 0;
2956 options[OptUTF8] = 1;
2957 state = edid_state();
2958 // Accept values
2959 if (isnormal(diag) && diag) {
2960 if (diag >= 10 && diag <= 2559)
2961 state.diagonal = diag;
2962 else
2963 fprintf(stderr, "Ignored diagonal, expected to be between 10 and 2559 inches.\n");
2964 }
2965 int ret = edid_from_file(input, stderr);
2966 return ret ? ret : state.parse_edid();
2967 }
2968
2969 #endif