summaryrefslogtreecommitdiff
path: root/edid-decode.c
blob: 6b02514a5c9c655d3ddea6fcbd1cd4b58cad7405 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
3300
3301
3302
3303
3304
3305
3306
3307
3308
3309
3310
3311
3312
3313
3314
3315
3316
3317
3318
3319
3320
3321
3322
3323
3324
3325
3326
3327
3328
3329
3330
3331
3332
3333
3334
3335
3336
3337
3338
3339
3340
3341
3342
3343
3344
3345
3346
3347
3348
3349
3350
3351
3352
3353
3354
3355
3356
3357
3358
3359
3360
3361
3362
3363
3364
3365
3366
3367
3368
3369
3370
3371
3372
3373
3374
3375
3376
3377
3378
3379
3380
3381
3382
3383
3384
3385
3386
3387
3388
3389
3390
3391
3392
3393
3394
3395
3396
3397
3398
3399
3400
3401
3402
3403
3404
3405
3406
3407
3408
3409
3410
3411
3412
3413
3414
3415
3416
3417
3418
3419
3420
3421
3422
3423
3424
3425
3426
3427
3428
3429
3430
3431
3432
3433
3434
3435
3436
3437
/*
 * Copyright 2006-2012 Red Hat, Inc.
 *
 * Permission is hereby granted, free of charge, to any person obtaining a
 * copy of this software and associated documentation files (the "Software"),
 * to deal in the Software without restriction, including without limitation
 * on the rights to use, copy, modify, merge, publish, distribute, sub
 * license, and/or sell copies of the Software, and to permit persons to whom
 * the Software is furnished to do so, subject to the following conditions:
 *
 * The above copyright notice and this permission notice (including the next
 * paragraph) shall be included in all copies or substantial portions of the
 * Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT.  IN NO EVENT SHALL
 * THE AUTHORS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
 * IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
 * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
 */
/* Author: Adam Jackson <ajax@nwnk.net> */
/* Maintainer: Hans Verkuil <hans.verkuil@cisco.com> */

#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <getopt.h>
#include <stdio.h>
#include <stdint.h>
#include <unistd.h>
#include <string.h>
#include <stdlib.h>
#include <time.h>
#include <ctype.h>
#include <math.h>

#define ARRAY_SIZE(x) (sizeof(x) / sizeof(*(x)))
#define min(a, b) ((a) < (b) ? (a) : (b))
#define max(a, b) ((a) > (b) ? (a) : (b))

enum {
	EDID_PAGE_SIZE = 128u
};

static int edid_minor = 0;
static int claims_one_point_oh = 0;
static int claims_one_point_two = 0;
static int claims_one_point_three = 0;
static int claims_one_point_four = 0;
static int nonconformant_digital_display = 0;
static int nonconformant_extension = 0;
static int did_detailed_timing = 0;
static int has_name_descriptor = 0;
static int has_serial_string = 0;
static int has_ascii_string = 0;
static int has_range_descriptor = 0;
static int has_preferred_timing = 0;
static int has_valid_checksum = 1;
static int has_valid_cta_checksum = 1;
static int has_valid_displayid_checksum = 1;
static int has_valid_cvt = 1;
static int has_valid_dummy_block = 1;
static int has_valid_serial_number = 0;
static int has_valid_serial_string = 0;
static int has_valid_ascii_string = 0;
static int has_valid_name_descriptor = 0;
static int has_valid_week = 0;
static int has_valid_year = 0;
static int has_valid_detailed_blocks = 0;
static int has_valid_descriptor_ordering = 1;
static int has_valid_descriptor_pad = 1;
static int has_valid_range_descriptor = 1;
static int has_valid_max_dotclock = 1;
static int has_valid_string_termination = 1;
static int empty_string = 0;
static int trailing_space = 0;
static int has_cta861 = 0;
static int has_640x480p60_est_timing = 0;
static int has_cta861_vic_1 = 0;
static int manufacturer_name_well_formed = 0;
static int seen_non_detailed_descriptor = 0;

static int warning_excessive_dotclock_correction = 0;
static int warning_zero_preferred_refresh = 0;
static int nonconformant_hf_vsdb_position = 0;
static int nonconformant_srgb_chromaticity = 0;
static int nonconformant_cta861_640x480 = 0;
static int nonconformant_hdmi_vsdb_tmds_rate = 0;
static int nonconformant_hf_vsdb_tmds_rate = 0;

static int min_hor_freq_hz = 0xfffffff;
static int max_hor_freq_hz = 0;
static int min_vert_freq_hz = 0xfffffff;
static int max_vert_freq_hz = 0;
static int max_pixclk_khz = 0;
static int mon_min_hor_freq_hz = 0;
static int mon_max_hor_freq_hz = 0;
static int mon_min_vert_freq_hz = 0;
static int mon_max_vert_freq_hz = 0;
static int mon_max_pixclk_khz = 0;
static unsigned supported_hdmi_vic_codes = 0;
static unsigned supported_hdmi_vic_vsb_codes = 0;

static int conformant = 1;

enum output_format {
	OUT_FMT_DEFAULT,
	OUT_FMT_HEX,
	OUT_FMT_RAW,
	OUT_FMT_CARRAY
};

/*
 * Options
 * Please keep in alphabetical order of the short option.
 * That makes it easier to see which options are still free.
 */
enum Option {
	OptCheck = 'c',
	OptExtract = 'e',
	OptHelp = 'h',
	OptOutputFormat = 'o',
	OptLast = 256
};

static char options[OptLast];

static struct option long_options[] = {
	{ "help", no_argument, 0, OptHelp },
	{ "output-format", required_argument, 0, OptOutputFormat },
	{ "extract", no_argument, 0, OptExtract },
	{ "check", no_argument, 0, OptCheck },
	{ 0, 0, 0, 0 }
};

static void usage(void)
{
	printf("Usage: edid-decode <options> [in [out]]\n"
	       "  [in]                  EDID file to parse. Read from standard input if none given\n"
	       "                        or if the input filename is '-'.\n"
	       "  [out]                 Output the read EDID to this file. Write to standard output\n"
	       "                        if the output filename is '-'.\n"
	       "\nOptions:\n"
	       "  -o, --output-format=<fmt>\n"
	       "                        if [out] is specified, then write the EDID in this format\n"
	       "                        <fmt> is one of:\n"
	       "                        hex:    hex numbers in ascii text (default for stdout)\n"
	       "                        raw:    binary data (default unless writing to stdout)\n"
	       "                        carray: c-program struct\n"
	       "  -c, --check           check if the EDID conforms to the standards\n"
	       "  -e, --extract         extract the contents of the first block in hex values\n"
	       "  -h, --help            display this help message\n");
}

struct value {
	int value;
	const char *description;
};

struct field {
	const char *name;
	int start, end;
	struct value *values;
	int n_values;
};

#define DEFINE_FIELD(n, var, s, e, ...)				\
static struct value var##_values[] =  {				\
	__VA_ARGS__						\
};								\
static struct field var = {					\
	.name = n,						\
	.start = s,		        			\
	.end = e,						\
	.values = var##_values,	        			\
	.n_values = ARRAY_SIZE(var##_values),			\
}

static void decode_value(struct field *field, int val, const char *prefix)
{
	struct value *v;
	int i;

	for (i = 0; i < field->n_values; i++) {
		v = &field->values[i];

		if (v->value == val)
			break;
	}

	if (i == field->n_values) {
		printf("%s%s: %d\n", prefix, field->name, val);
		return;
	}

	printf("%s%s: %s (%d)\n", prefix, field->name, v->description, val);
}

static void _decode(struct field **fields, int n_fields, int data, const char *prefix)
{
	int i;

	for (i = 0; i < n_fields; i++) {
		struct field *f = fields[i];
		int field_length = f->end - f->start + 1;
		int val;

		if (field_length == 32)
			val = data;
		else
			val = (data >> f->start) & ((1 << field_length) - 1);

		decode_value(f, val, prefix);
	}
}

#define decode(fields, data, prefix)    \
	_decode(fields, ARRAY_SIZE(fields), data, prefix)

static char *manufacturer_name(const unsigned char *x)
{
	static char name[4];

	name[0] = ((x[0] & 0x7C) >> 2) + '@';
	name[1] = ((x[0] & 0x03) << 3) + ((x[1] & 0xE0) >> 5) + '@';
	name[2] = (x[1] & 0x1F) + '@';
	name[3] = 0;

	if (isupper(name[0]) && isupper(name[1]) && isupper(name[2]))
		manufacturer_name_well_formed = 1;

	return name;
}

/*
 * Copied from xserver/hw/xfree86/modes/xf86cvt.c
 */
static void edid_cvt_mode(int HDisplay, int VDisplay,
			  int VRefresh, int Reduced,
			  unsigned *MinHFreq, unsigned *MaxHFreq,
			  unsigned *MaxClock)
{
	/* 1) top/bottom margin size (% of height) - default: 1.8 */
#define CVT_MARGIN_PERCENTAGE 1.8

	/* 2) character cell horizontal granularity (pixels) - default 8 */
#define CVT_H_GRANULARITY 8

	/* 4) Minimum vertical porch (lines) - default 3 */
#define CVT_MIN_V_PORCH 3

	/* 4) Minimum number of vertical back porch lines - default 6 */
#define CVT_MIN_V_BPORCH 6

	/* Pixel Clock step (kHz) */
#define CVT_CLOCK_STEP 250

	float HPeriod;
	unsigned HTotal, Clock, HorFreq;
	int VSync;

	/* 2. Horizontal pixels */
	HDisplay = HDisplay - (HDisplay % CVT_H_GRANULARITY);

	/* Determine VSync Width from aspect ratio */
	if (!(VDisplay % 3) && ((VDisplay * 4 / 3) == HDisplay))
		VSync = 4;
	else if (!(VDisplay % 9) && ((VDisplay * 16 / 9) == HDisplay))
		VSync = 5;
	else if (!(VDisplay % 10) && ((VDisplay * 16 / 10) == HDisplay))
		VSync = 6;
	else if (!(VDisplay % 4) && ((VDisplay * 5 / 4) == HDisplay))
		VSync = 7;
	else if (!(VDisplay % 9) && ((VDisplay * 15 / 9) == HDisplay))
		VSync = 7;
	else                        /* Custom */
		VSync = 10;

	if (!Reduced) {             /* simplified GTF calculation */

		/* 4) Minimum time of vertical sync + back porch interval (µs)
		 * default 550.0 */
#define CVT_MIN_VSYNC_BP 550.0

		/* 3) Nominal HSync width (% of line period) - default 8 */
#define CVT_HSYNC_PERCENTAGE 8

		float HBlankPercentage;
		int HBlank;

		/* 8. Estimated Horizontal period */
		HPeriod = ((float) (1000000.0 / VRefresh - CVT_MIN_VSYNC_BP)) /
			(VDisplay + CVT_MIN_V_PORCH);

		/* 5) Definition of Horizontal blanking time limitation */
		/* Gradient (%/kHz) - default 600 */
#define CVT_M_FACTOR 600

		/* Offset (%) - default 40 */
#define CVT_C_FACTOR 40

		/* Blanking time scaling factor - default 128 */
#define CVT_K_FACTOR 128

		/* Scaling factor weighting - default 20 */
#define CVT_J_FACTOR 20

#define CVT_M_PRIME (CVT_M_FACTOR * CVT_K_FACTOR / 256)
#define CVT_C_PRIME ((CVT_C_FACTOR - CVT_J_FACTOR) * CVT_K_FACTOR / 256 + CVT_J_FACTOR)

		/* 12. Find ideal blanking duty cycle from formula */
		HBlankPercentage = CVT_C_PRIME - CVT_M_PRIME * HPeriod / 1000.0;

		/* 13. Blanking time */
		if (HBlankPercentage < 20)
			HBlankPercentage = 20;

		HBlank = HDisplay * HBlankPercentage / (100.0 - HBlankPercentage);
		HBlank -= HBlank % (2 * CVT_H_GRANULARITY);

		/* 14. Find total number of pixels in a line. */
		HTotal = HDisplay + HBlank;
	}
	else {                      /* Reduced blanking */
		/* Minimum vertical blanking interval time (µs) - default 460 */
#define CVT_RB_MIN_VBLANK 460.0

		/* Fixed number of clocks for horizontal sync */
#define CVT_RB_H_SYNC 32.0

		/* Fixed number of clocks for horizontal blanking */
#define CVT_RB_H_BLANK 160.0

		/* Fixed number of lines for vertical front porch - default 3 */
#define CVT_RB_VFPORCH 3

		int VBILines;

		/* 8. Estimate Horizontal period. */
		HPeriod = ((float) (1000000.0 / VRefresh - CVT_RB_MIN_VBLANK)) / VDisplay;

		/* 9. Find number of lines in vertical blanking */
		VBILines = ((float) CVT_RB_MIN_VBLANK) / HPeriod + 1;

		/* 10. Check if vertical blanking is sufficient */
		if (VBILines < (CVT_RB_VFPORCH + VSync + CVT_MIN_V_BPORCH))
			VBILines = CVT_RB_VFPORCH + VSync + CVT_MIN_V_BPORCH;

		/* 12. Find total number of pixels in a line */
		HTotal = HDisplay + CVT_RB_H_BLANK;
	}

	/* 15/13. Find pixel clock frequency (kHz for xf86) */
	Clock = HTotal * 1000.0 / HPeriod;
	Clock -= Clock % CVT_CLOCK_STEP;
	HorFreq = (Clock * 1000) / HTotal;

	*MinHFreq = min(*MinHFreq, HorFreq);
	*MaxHFreq = max(*MaxHFreq, HorFreq);
	*MaxClock = max(*MaxClock, Clock);
	min_hor_freq_hz = min(min_hor_freq_hz, HorFreq);
	max_hor_freq_hz = max(max_hor_freq_hz, HorFreq);
	max_pixclk_khz = max(max_pixclk_khz, Clock);
}

static int detailed_cvt_descriptor(const unsigned char *x, int first)
{
	const unsigned char empty[3] = { 0, 0, 0 };
	const char *ratio;
	char *names[] = { "50", "60", "75", "85" };
	int width, height;
	int valid = 1;
	int fifty = 0, sixty = 0, seventyfive = 0, eightyfive = 0, reduced = 0;
	int min_refresh = 0xfffffff, max_refresh = 0;

	if (!first && !memcmp(x, empty, 3))
		return valid;

	height = x[0];
	height |= (x[1] & 0xf0) << 4;
	height++;
	height *= 2;

	switch (x[1] & 0x0c) {
	case 0x00:
		width = 8 * (((height * 4) / 3) / 8);
		ratio = "4:3";
		break;
	case 0x04:
		width = 8 * (((height * 16) / 9) / 8);
		ratio = "16:9";
		break;
	case 0x08:
		width = 8 * (((height * 16) / 10) / 8);
		ratio = "16:10";
		break;
	case 0x0c:
		width = 8 * (((height * 15) / 9) / 8);
		ratio = "15:9";
		break;
	}

	if (x[1] & 0x03)
		valid = 0;
	if (x[2] & 0x80)
		valid = 0;
	if (!(x[2] & 0x1f))
		valid = 0;

	fifty	= (x[2] & 0x10);
	sixty	= (x[2] & 0x08);
	seventyfive = (x[2] & 0x04);
	eightyfive  = (x[2] & 0x02);
	reduced	= (x[2] & 0x01);

	min_refresh = (fifty ? 50 : (sixty ? 60 : (seventyfive ? 75 : (eightyfive ? 85 : min_refresh))));
	max_refresh = (eightyfive ? 85 : (seventyfive ? 75 : (sixty ? 60 : (fifty ? 50 : max_refresh))));

	if (!valid) {
		printf("    (broken)\n");
	} else {
		unsigned min_hfreq = ~0;
		unsigned max_hfreq = 0;
		unsigned max_clock = 0;

		min_vert_freq_hz = min(min_vert_freq_hz, min_refresh);
		max_vert_freq_hz = max(max_vert_freq_hz, max_refresh);

		if (fifty)
			edid_cvt_mode(width, height, 50, 0,
				      &min_hfreq, &max_hfreq, &max_clock);
		if (sixty)
			edid_cvt_mode(width, height, 60, 0,
				      &min_hfreq, &max_hfreq, &max_clock);
		if (seventyfive)
			edid_cvt_mode(width, height, 75, 0,
				      &min_hfreq, &max_hfreq, &max_clock);
		if (eightyfive)
			edid_cvt_mode(width, height, 75, 0,
				      &min_hfreq, &max_hfreq, &max_clock);
		if (reduced)
			edid_cvt_mode(width, height, 60, 1,
				      &min_hfreq, &max_hfreq, &max_clock);

		printf("    %dx%d @ ( %s%s%s%s%s) Hz %s (%s%s preferred) HorFreq: %d-%d Hz MaxClock: %.3f MHz\n",
		       width, height,
		       fifty ? "50 " : "",
		       sixty ? "60 " : "",
		       seventyfive ? "75 " : "",
		       eightyfive ? "85 " : "",
		       reduced ? "60RB " : "",
		       ratio,
		       names[(x[2] & 0x60) >> 5],
		       (((x[2] & 0x60) == 0x20) && reduced) ? "RB" : "",
		       min_hfreq, max_hfreq, max_clock / 1000000.0);
	}

	return valid;
}

/* extract a string from a detailed subblock, checking for termination */
static char *extract_string(const unsigned char *x, int *valid, int len)
{
	static char ret[EDID_PAGE_SIZE];
	int i, seen_newline = 0;

	memset(ret, 0, sizeof(ret));
	*valid = 1;

	for (i = 0; i < len; i++) {
		if (isgraph(x[i])) {
			ret[i] = x[i];
		} else if (!seen_newline) {
			if (x[i] == 0x0a) {
				seen_newline = 1;
				if (!i) {
					empty_string = 1;
					*valid = 0;
				} else if (ret[i - 1] == 0x20) {
					trailing_space = 1;
					*valid = 0;
				}
			} else if (x[i] == 0x20) {
				ret[i] = x[i];
			} else {
				has_valid_string_termination = 0;
				*valid = 0;
				return ret;
			}
		} else if (x[i] != 0x20) {
			has_valid_string_termination = 0;
			*valid = 0;
			return ret;
		}
	}
	/* Does the string end with a space? */
	if (!seen_newline && ret[len - 1] == 0x20) {
		trailing_space = 1;
		*valid = 0;
	}

	return ret;
}

static const struct {
	int x, y, refresh, ratio_w, ratio_h;
	int hor_freq_hz, pixclk_khz, interlaced;
} established_timings[] = {
	/* 0x23 bit 7 - 0 */
	{720, 400, 70, 9, 5, 31469, 28320},
	{720, 400, 88, 9, 5, 39500, 35500},
	{640, 480, 60, 4, 3, 31469, 25175},
	{640, 480, 67, 4, 3, 35000, 30240},
	{640, 480, 72, 4, 3, 37900, 31500},
	{640, 480, 75, 4, 3, 37500, 31500},
	{800, 600, 56, 4, 3, 35200, 36000},
	{800, 600, 60, 4, 3, 37900, 40000},
	/* 0x24 bit 7 - 0 */
	{800, 600, 72, 4, 3, 48100, 50000},
	{800, 600, 75, 4, 3, 46900, 49500},
	{832, 624, 75, 4, 3, 49726, 57284},
	{1280, 768, 87, 5, 3, 35522, 44900, 1},
	{1024, 768, 60, 4, 3, 48400, 65000},
	{1024, 768, 70, 4, 3, 56500, 75000},
	{1024, 768, 75, 4, 3, 60000, 78750},
	{1280, 1024, 75, 5, 4, 80000, 135000},
	/* 0x25 bit 7*/
	{1152, 870, 75, 192, 145, 67500, 108000},
};

static const struct {
	int x, y, refresh, ratio_w, ratio_h;
	int hor_freq_hz, pixclk_khz, rb;
} established_timings3[] = {
	/* 0x06 bit 7 - 0 */
	{640, 350, 85, 64, 35, 37900, 31500},
	{640, 400, 85, 16, 10, 37900, 31500},
	{720, 400, 85, 9, 5, 37900, 35500},
	{640, 480, 85, 4, 3, 43300, 36000},
	{848, 480, 60, 53, 30, 31000, 33750},
	{800, 600, 85, 4, 3, 53700, 56250},
	{1024, 768, 85, 4, 3, 68700, 94500},
	{1152, 864, 75, 4, 3, 67500, 108000},
	/* 0x07 bit 7 - 0 */
	{1280, 768, 60, 5, 3, 47400, 68250, 1},
	{1280, 768, 60, 5, 3, 47800, 79500},
	{1280, 768, 75, 5, 3, 60300, 102250},
	{1280, 768, 85, 5, 3, 68600, 117500},
	{1280, 960, 60, 4, 3, 60000, 108000},
	{1280, 960, 85, 4, 3, 85900, 148500},
	{1280, 1024, 60, 5, 4, 64000, 108000},
	{1280, 1024, 85, 5, 4, 91100, 157500},
	/* 0x08 bit 7 - 0 */
	{1360, 768, 60, 85, 48, 47700, 85500},
	{1440, 900, 60, 16, 10, 55500, 88750, 1},
	{1440, 900, 60, 16, 10, 65300, 121750},
	{1440, 900, 75, 16, 10, 82300, 156000},
	{1440, 900, 85, 16, 10, 93900, 179500},
	{1400, 1050, 60, 4, 3, 64700, 101000, 1},
	{1400, 1050, 60, 4, 3, 65300, 121750},
	{1400, 1050, 75, 4, 3, 82300, 156000},
	/* 0x09 bit 7 - 0 */
	{1400, 1050, 85, 4, 3, 93900, 179500},
	{1680, 1050, 60, 16, 10, 64700, 119000, 1},
	{1680, 1050, 60, 16, 10, 65300, 146250},
	{1680, 1050, 75, 16, 10, 82300, 187000},
	{1680, 1050, 85, 16, 10, 93900, 214750},
	{1600, 1200, 60, 4, 3, 75000, 162000},
	{1600, 1200, 65, 4, 3, 81300, 175500},
	{1600, 1200, 70, 4, 3, 87500, 189000},
	/* 0x0a bit 7 - 0 */
	{1600, 1200, 75, 4, 3, 93800, 202500},
	{1600, 1200, 85, 4, 3, 106300, 229500},
	{1792, 1344, 60, 4, 3, 83600, 204750},
	{1792, 1344, 75, 4, 3, 106300, 261000},
	{1856, 1392, 60, 4, 3, 86300, 218250},
	{1856, 1392, 75, 4, 3, 112500, 288000},
	{1920, 1200, 60, 16, 10, 74000, 154000, 1},
	{1920, 1200, 60, 16, 10, 74600, 193250},
	/* 0x0b bit 7 - 4 */
	{1920, 1200, 75, 16, 10, 94000, 245250},
	{1920, 1200, 85, 16, 10, 107200, 281250},
	{1920, 1440, 60, 4, 3, 90000, 234000},
	{1920, 1440, 75, 4, 3, 112500, 297000},
};

static void print_standard_timing(uint8_t b1, uint8_t b2)
{
	int ratio_w, ratio_h;
	unsigned int x, y, refresh;
	int pixclk_khz = 0, hor_freq_hz = 0;
	int i;

	if (b1 == 0x01 && b2 == 0x01)
		return;

	if (b1 == 0) {
		printf("non-conformant standard timing (0 horiz)\n");
		return;
	}
	x = (b1 + 31) * 8;
	switch ((b2 >> 6) & 0x3) {
	case 0x00:
		if (claims_one_point_three) {
			y = x * 10 / 16;
			ratio_w = 16;
			ratio_h = 10;
		} else {
			y = x;
			ratio_w = 1;
			ratio_h = 1;
		}
		break;
	case 0x01:
		y = x * 3 / 4;
		ratio_w = 4;
		ratio_h = 3;
		break;
	case 0x02:
		y = x * 4 / 5;
		ratio_w = 5;
		ratio_h = 4;
		break;
	case 0x03:
		y = x * 9 / 16;
		ratio_w = 16;
		ratio_h = 9;
		break;
	}
	refresh = 60 + (b2 & 0x3f);

	min_vert_freq_hz = min(min_vert_freq_hz, refresh);
	max_vert_freq_hz = max(max_vert_freq_hz, refresh);
	for (i = 0; i < ARRAY_SIZE(established_timings); i++) {
		if (established_timings[i].x == x &&
		    established_timings[i].y == y &&
		    established_timings[i].refresh == refresh &&
		    established_timings[i].ratio_w == ratio_w &&
		    established_timings[i].ratio_h == ratio_h) {
			pixclk_khz = established_timings[i].pixclk_khz;
			hor_freq_hz = established_timings[i].hor_freq_hz;
			break;
		}
	}
	if (pixclk_khz == 0) {
		for (i = 0; i < ARRAY_SIZE(established_timings3); i++) {
			if (established_timings3[i].x == x &&
			    established_timings3[i].y == y &&
			    established_timings3[i].refresh == refresh &&
			    established_timings3[i].ratio_w == ratio_w &&
			    established_timings3[i].ratio_h == ratio_h) {
				pixclk_khz = established_timings3[i].pixclk_khz;
				hor_freq_hz = established_timings3[i].hor_freq_hz;
				break;
			}
		}
	}
	/* TODO: this should also check DMT timings and GTF/CVT */
	if (pixclk_khz) {
		min_hor_freq_hz = min(min_hor_freq_hz, hor_freq_hz);
		max_hor_freq_hz = max(max_hor_freq_hz, hor_freq_hz);
		max_pixclk_khz = max(max_pixclk_khz, pixclk_khz);
		printf("  %dx%d@%dHz %d:%d HorFreq: %d Hz Clock: %.3f MHz\n",
		       x, y, refresh, ratio_w, ratio_h,
		       hor_freq_hz, pixclk_khz / 1000.0);
	} else {
		printf("  %dx%d@%dHz %d:%d\n",
		       x, y, refresh, ratio_w, ratio_h);
	}
}

/* 1 means valid data */
static int detailed_block(const unsigned char *x, int in_extension)
{
	int ha, hbl, hso, hspw, hborder, va, vbl, vso, vspw, vborder;
	int refresh, pixclk_khz;
	int i;
	char phsync, pvsync, *syncmethod, *stereo;

#if 0
	printf("Hex of detail: ");
	for (i = 0; i < 18; i++)
		printf("%02x", x[i]);
	printf("\n");
#endif

	if (x[0] == 0 && x[1] == 0) {
		/* Monitor descriptor block, not detailed timing descriptor. */
		if (x[2] != 0) {
			/* 1.3, 3.10.3 */
			printf("Monitor descriptor block has byte 2 nonzero (0x%02x)\n",
			       x[2]);
			has_valid_descriptor_pad = 0;
		}
		if (x[3] != 0xfd && x[4] != 0x00) {
			/* 1.3, 3.10.3 */
			printf("Monitor descriptor block has byte 4 nonzero (0x%02x)\n",
			       x[4]);
			has_valid_descriptor_pad = 0;
		}

		seen_non_detailed_descriptor = 1;
		if (x[3] <= 0xF) {
			/*
			 * in principle we can decode these, if we know what they are.
			 * 0x0f seems to be common in laptop panels.
			 * 0x0e is used by EPI: http://www.epi-standard.org/
			 */
			printf("Manufacturer-specified data, tag %d\n", x[3]);
			return 1;
		}
		switch (x[3]) {
		case 0x10:
			printf("Dummy block\n");
			for (i = 5; i < 18; i++)
				if (x[i] != 0x00)
					has_valid_dummy_block = 0;
			return 1;
		case 0xF7:
			printf("Established timings III:\n");
			for (i = 0; i < 44; i++) {
				if (x[6 + i / 8] & (1 << (7 - i % 8))) {
					printf("  %dx%d@%dHz %s%u:%u HorFreq: %d Hz Clock: %.3f MHz\n",
					       established_timings3[i].x,
					       established_timings3[i].y, established_timings3[i].refresh,
					       established_timings3[i].rb ? "RB " : "",
					       established_timings3[i].ratio_w, established_timings3[i].ratio_h,
					       established_timings3[i].hor_freq_hz,
					       established_timings3[i].pixclk_khz / 1000.0);
					min_vert_freq_hz = min(min_vert_freq_hz, established_timings3[i].refresh);
					max_vert_freq_hz = max(max_vert_freq_hz, established_timings3[i].refresh);
					min_hor_freq_hz = min(min_hor_freq_hz, established_timings3[i].hor_freq_hz);
					max_hor_freq_hz = max(max_hor_freq_hz, established_timings3[i].hor_freq_hz);
					max_pixclk_khz = max(max_pixclk_khz, established_timings3[i].pixclk_khz);
				}
			}
			return 1;
		case 0xF8: {
			int valid_cvt = 1; /* just this block */
			printf("CVT 3-byte code descriptor:\n");
			if (x[5] != 0x01) {
				has_valid_cvt = 0;
				return 0;
			}
			for (i = 0; i < 4; i++)
				valid_cvt &= detailed_cvt_descriptor(x + 6 + (i * 3), (i == 0));
			has_valid_cvt &= valid_cvt;
			return valid_cvt;
		}
		case 0xF9:
			printf("Color management data:\n");
			printf("  Version:  %d\n", x[5]);
			printf("  Red a3:   %.2f\n", (short)(x[6] | (x[7] << 8)) / 100.0);
			printf("  Red a2:   %.2f\n", (short)(x[8] | (x[9] << 8)) / 100.0);
			printf("  Green a3: %.2f\n", (short)(x[10] | (x[11] << 8)) / 100.0);
			printf("  Green a2: %.2f\n", (short)(x[12] | (x[13] << 8)) / 100.0);
			printf("  Blue a3:  %.2f\n", (short)(x[14] | (x[15] << 8)) / 100.0);
			printf("  Blue a2:  %.2f\n", (short)(x[16] | (x[17] << 8)) / 100.0);
			return 1;
		case 0xFA:
			printf("More standard timings:\n");
			for (i = 0; i < 6; i++)
				print_standard_timing(x[5 + i * 2], x[5 + i * 2 + 1]);
			return 1;
		case 0xFB: {
			unsigned w_x, w_y;
			unsigned gamma;

			printf("Color point:\n");
			w_x = (x[7] << 2) | ((x[6] >> 2) & 3);
			w_y = (x[8] << 2) | (x[6] & 3);
			gamma = x[9];
			printf("  Index: %u White: 0.%04u, 0.%04u", x[5],
			       (w_x * 10000) / 1024, (w_y * 10000) / 1024);
			if (gamma == 0xff)
				printf(" Gamma: is defined in an extension block");
			else
				printf(" Gamma: %.2f", ((gamma + 100.0) / 100.0));
			printf("\n");
			if (x[10] == 0)
				return 1;
			w_x = (x[12] << 2) | ((x[11] >> 2) & 3);
			w_y = (x[13] << 2) | (x[11] & 3);
			gamma = x[14];
			printf("  Index: %u White: 0.%04u, 0.%04u", x[10],
			       (w_x * 10000) / 1024, (w_y * 10000) / 1024);
			if (gamma == 0xff)
				printf(" Gamma: is defined in an extension block");
			else
				printf(" Gamma: %.2f", ((gamma + 100.0) / 100.0));
			printf("\n");
			return 1;
		}
		case 0xFC:
			has_name_descriptor = 1;
			printf("Monitor name: %s\n",
			       extract_string(x + 5, &has_valid_name_descriptor, 13));
			return 1;
		case 0xFD: {
			int h_max_offset = 0, h_min_offset = 0;
			int v_max_offset = 0, v_min_offset = 0;
			int is_cvt = 0;
			has_range_descriptor = 1;
			char *range_class = "";
			/* 
			 * XXX todo: implement feature flags, vtd blocks
			 * XXX check: ranges are well-formed; block termination if no vtd
			 */
			if (claims_one_point_four) {
				if (x[4] & 0x02) {
					v_max_offset = 255;
					if (x[4] & 0x01) {
						v_min_offset = 255;
					}
				}
				if (x[4] & 0x04) {
					h_max_offset = 255;
					if (x[4] & 0x03) {
						h_min_offset = 255;
					}
				}
			} else if (x[4]) {
				has_valid_range_descriptor = 0;
			}

			/*
			 * despite the values, this is not a bitfield.
			 */
			switch (x[10]) {
			case 0x00: /* default gtf */
				range_class = "GTF";
				break;
			case 0x01: /* range limits only */
				range_class = "bare limits";
				if (!claims_one_point_four)
					has_valid_range_descriptor = 0;
				break;
			case 0x02: /* secondary gtf curve */
				range_class = "GTF with icing";
				break;
			case 0x04: /* cvt */
				range_class = "CVT";
				is_cvt = 1;
				if (!claims_one_point_four)
					has_valid_range_descriptor = 0;
				break;
			default: /* invalid */
				has_valid_range_descriptor = 0;
				range_class = "invalid";
				break;
			}

			if (x[5] + v_min_offset > x[6] + v_max_offset)
				has_valid_range_descriptor = 0;
			mon_min_vert_freq_hz = x[5] + v_min_offset;
			mon_max_vert_freq_hz = x[6] + v_max_offset;
			if (x[7] + h_min_offset > x[8] + h_max_offset)
				has_valid_range_descriptor = 0;
			mon_min_hor_freq_hz = (x[7] + h_min_offset) * 1000;
			mon_max_hor_freq_hz = (x[8] + h_max_offset) * 1000;
			printf("Monitor ranges (%s): %d-%dHz V, %d-%dkHz H",
			       range_class,
			       x[5] + v_min_offset, x[6] + v_max_offset,
			       x[7] + h_min_offset, x[8] + h_max_offset);
			if (x[9]) {
				mon_max_pixclk_khz = x[9] * 10000;
				printf(", max dotclock %dMHz\n", x[9] * 10);
			} else {
				if (claims_one_point_four)
					has_valid_max_dotclock = 0;
				printf("\n");
			}

			if (is_cvt) {
				int max_h_pixels = 0;

				printf("CVT version %d.%d\n", (x[11] & 0xf0) >> 4, x[11] & 0x0f);

				if (x[12] & 0xfc) {
					int raw_offset = (x[12] & 0xfc) >> 2;
					printf("Real max dotclock: %.2fMHz\n",
					       (x[9] * 10) - (raw_offset * 0.25));
					if (raw_offset >= 40)
						warning_excessive_dotclock_correction = 1;
				}

				max_h_pixels = x[12] & 0x03;
				max_h_pixels <<= 8;
				max_h_pixels |= x[13];
				max_h_pixels *= 8;
				if (max_h_pixels)
					printf("Max active pixels per line: %d\n", max_h_pixels);

				printf("Supported aspect ratios: %s %s %s %s %s\n",
				       x[14] & 0x80 ? "4:3" : "",
				       x[14] & 0x40 ? "16:9" : "",
				       x[14] & 0x20 ? "16:10" : "",
				       x[14] & 0x10 ? "5:4" : "",
				       x[14] & 0x08 ? "15:9" : "");
				if (x[14] & 0x07)
					has_valid_range_descriptor = 0;

				printf("Preferred aspect ratio: ");
				switch((x[15] & 0xe0) >> 5) {
				case 0x00: printf("4:3"); break;
				case 0x01: printf("16:9"); break;
				case 0x02: printf("16:10"); break;
				case 0x03: printf("5:4"); break;
				case 0x04: printf("15:9"); break;
				default: printf("(broken)"); break;
				}
				printf("\n");

				if (x[15] & 0x08)
					printf("Supports CVT standard blanking\n");
				if (x[15] & 0x10)
					printf("Supports CVT reduced blanking\n");

				if (x[15] & 0x07)
					has_valid_range_descriptor = 0;

				if (x[16] & 0xf0) {
					printf("Supported display scaling:\n");
					if (x[16] & 0x80)
						printf("    Horizontal shrink\n");
					if (x[16] & 0x40)
						printf("    Horizontal stretch\n");
					if (x[16] & 0x20)
						printf("    Vertical shrink\n");
					if (x[16] & 0x10)
						printf("    Vertical stretch\n");
				}

				if (x[16] & 0x0f)
					has_valid_range_descriptor = 0;

				if (x[17])
					printf("Preferred vertical refresh: %d Hz\n", x[17]);
				else
					warning_zero_preferred_refresh = 1;
			}

			/*
			 * Slightly weird to return a global, but I've never seen any
			 * EDID block wth two range descriptors, so it's harmless.
			 */
			return has_valid_range_descriptor;
		}
		case 0xFE:
			/*
			 * TODO: Two of these in a row, in the third and fourth slots,
			 * seems to be specified by SPWG: http://www.spwg.org/
			 */
			has_ascii_string = 1;
			printf("ASCII string: %s\n",
			       extract_string(x + 5, &has_valid_ascii_string, 13));
			return 1;
		case 0xFF:
			has_serial_string = 1;
			printf("Serial number: %s\n",
			       extract_string(x + 5, &has_valid_serial_string, 13));
			return 1;
		default:
			printf("Unknown monitor description type %d\n", x[3]);
			return 0;
		}
	}

	if (seen_non_detailed_descriptor && !in_extension) {
		has_valid_descriptor_ordering = 0;
	}

	did_detailed_timing = 1;
	ha = (x[2] + ((x[4] & 0xF0) << 4));
	hbl = (x[3] + ((x[4] & 0x0F) << 8));
	hso = (x[8] + ((x[11] & 0xC0) << 2));
	hspw = (x[9] + ((x[11] & 0x30) << 4));
	hborder = x[15];
	va = (x[5] + ((x[7] & 0xF0) << 4));
	vbl = (x[6] + ((x[7] & 0x0F) << 8));
	vso = ((x[10] >> 4) + ((x[11] & 0x0C) << 2));
	vspw = ((x[10] & 0x0F) + ((x[11] & 0x03) << 4));
	vborder = x[16];
	switch ((x[17] & 0x18) >> 3) {
	case 0x00:
		syncmethod = " analog composite";
		break;
	case 0x01:
		syncmethod = " bipolar analog composite";
		break;
	case 0x02:
		syncmethod = " digital composite";
		break;
	case 0x03:
		syncmethod = "";
		break;
	}
	pvsync = (x[17] & (1 << 2)) ? '+' : '-';
	phsync = (x[17] & (1 << 1)) ? '+' : '-';
	switch (x[17] & 0x61) {
	case 0x20:
		stereo = "field sequential L/R";
		break;
	case 0x40:
		stereo = "field sequential R/L";
		break;
	case 0x21:
		stereo = "interleaved right even";
		break;
	case 0x41:
		stereo = "interleaved left even";
		break;
	case 0x60:
		stereo = "four way interleaved";
		break;
	case 0x61:
		stereo = "side by side interleaved";
		break;
	default:
		stereo = "";
		break;
	}

	pixclk_khz = (x[0] + (x[1] << 8)) * 10;
	refresh = (pixclk_khz * 1000) / ((ha + hbl) * (va + vbl));
	printf("Detailed mode: Clock %.3f MHz, %d mm x %d mm\n"
	       "               %4d %4d %4d %4d hborder %d\n"
	       "               %4d %4d %4d %4d vborder %d\n"
	       "               %chsync %cvsync%s%s %s\n"
	       "               VertFreq: %d Hz, HorFreq: %d Hz\n",
	       pixclk_khz / 1000.0,
	       (x[12] + ((x[14] & 0xF0) << 4)),
	       (x[13] + ((x[14] & 0x0F) << 8)),
	       ha, ha + hso, ha + hso + hspw, ha + hbl, hborder,
	       va, va + vso, va + vso + vspw, va + vbl, vborder,
	       phsync, pvsync, syncmethod, x[17] & 0x80 ? " interlaced" : "",
	       stereo, refresh, (pixclk_khz * 1000) / (ha + hbl)
	      );
	min_vert_freq_hz = min(min_vert_freq_hz, refresh);
	max_vert_freq_hz = max(max_vert_freq_hz, refresh);
	min_hor_freq_hz = min(min_hor_freq_hz, (pixclk_khz * 1000) / (ha + hbl));
	max_hor_freq_hz = max(max_hor_freq_hz, (pixclk_khz * 1000) / (ha + hbl));
	max_pixclk_khz = max(max_pixclk_khz, pixclk_khz);
	/* XXX flag decode */

	return 1;
}

static int do_checksum(const unsigned char *x, size_t len)
{
	unsigned char check = x[len - 1];
	unsigned char sum = 0;
	int i;

	printf("Checksum: 0x%hx", check);

	for (i = 0; i < len-1; i++)
		sum += x[i];

	if ((unsigned char)(check + sum) != 0) {
		printf(" (should be 0x%hx)\n", -sum & 0xff);
		return 0;
	}

	printf(" (valid)\n");
	return 1;
}

/* CTA extension */

static const char *audio_ext_format(unsigned char x)
{
	switch (x) {
	case 4: return "MPEG-4 HE AAC";
	case 5: return "MPEG-4 HE AAC v2";
	case 6: return "MPEG-4 AAC LC";
	case 7: return "DRA";
	case 8: return "MPEG-4 HE AAC + MPEG Surround";
	case 10: return "MPEG-4 AAC + MPEG Surround";
	case 11: return "MPEG-H 3D Audio";
	case 12: return "AC-4";
	case 13: return "L-PCM 3D Audio";
	default: return "RESERVED";
	}
	return "BROKEN"; /* can't happen */
}

static const char *audio_format(unsigned char x)
{
	switch (x) {
	case 0: return "RESERVED";
	case 1: return "Linear PCM";
	case 2: return "AC-3";
	case 3: return "MPEG 1 (Layers 1 & 2)";
	case 4: return "MPEG 1 Layer 3 (MP3)";
	case 5: return "MPEG2 (multichannel)";
	case 6: return "AAC";
	case 7: return "DTS";
	case 8: return "ATRAC";
	case 9: return "One Bit Audio";
	case 10: return "Dolby Digital+";
	case 11: return "DTS-HD";
	case 12: return "MAT (MLP)";
	case 13: return "DST";
	case 14: return "WMA Pro";
	case 15: return "RESERVED";
	}
	return "BROKEN"; /* can't happen */
}

static void cta_audio_block(const unsigned char *x, unsigned int length)
{
	int i, format, ext_format = 0;

	if (length % 3) {
		printf("Broken CTA audio block length %d\n", length);
		/* XXX non-conformant */
		return;
	}

	for (i = 0; i < length; i += 3) {
		format = (x[i] & 0x78) >> 3;
		ext_format = (x[i + 2] & 0xf8) >> 3;
		if (format != 15)
			printf("    %s, max channels %d\n", audio_format(format),
			       (x[i] & 0x07)+1);
		else if (ext_format == 13)
			printf("    %s, max channels %d\n", audio_ext_format(ext_format),
			       (((x[i + 1] & 0x80) >> 3) | ((x[i] & 0x80) >> 4) |
				(x[i] & 0x07))+1);
		else
			printf("    %s, max channels %d\n", audio_ext_format(ext_format),
			       (x[i] & 0x07)+1);
		printf("      Supported sample rates (kHz):%s%s%s%s%s%s%s\n",
		       (x[i+1] & 0x40) ? " 192" : "",
		       (x[i+1] & 0x20) ? " 176.4" : "",
		       (x[i+1] & 0x10) ? " 96" : "",
		       (x[i+1] & 0x08) ? " 88.2" : "",
		       (x[i+1] & 0x04) ? " 48" : "",
		       (x[i+1] & 0x02) ? " 44.1" : "",
		       (x[i+1] & 0x01) ? " 32" : "");
		if (format == 1 || ext_format == 13) {
			printf("      Supported sample sizes (bits):%s%s%s\n",
			       (x[i+2] & 0x04) ? " 24" : "",
			       (x[i+2] & 0x02) ? " 20" : "",
			       (x[i+2] & 0x01) ? " 16" : "");
		} else if (format <= 8) {
			printf("      Maximum bit rate: %d kb/s\n", x[i+2] * 8);
		} else if (format == 14) {
			printf("      Profile: %d\n", x[i+2] & 7);
		} else if ((ext_format >= 4 && ext_format <= 6) ||
			   ext_format == 8 || ext_format == 10) {
			printf("      AAC audio frame lengths:%s%s\n",
			       (x[i+2] & 4) ? " 1024_TL" : "",
			       (x[i+2] & 2) ? " 960_TL" : "");
			if (ext_format >= 8 && (x[i+2] & 1))
				printf("      Supports %s signaled MPEG Surround data\n",
				       (x[i+2] & 1) ? "implicitly and explicitly" : "only implicitly");
		}
	}
}

struct edid_cta_mode {
	const char *name;
	int refresh, hor_freq_hz, pixclk_khz;
};

static struct edid_cta_mode edid_cta_modes1[] = {
	/* VIC 1 */
	{"640x480@60Hz 4:3", 60, 31469, 25175},
	{"720x480@60Hz 4:3", 60, 31469, 27000},
	{"720x480@60Hz 16:9", 60, 31469, 27000},
	{"1280x720@60Hz 16:9", 60, 45000, 74250},
	{"1920x1080i@60Hz 16:9", 60, 33750, 74250},
	{"1440x480i@60Hz 4:3", 60, 15734, 27000},
	{"1440x480i@60Hz 16:9", 60, 15734, 27000},
	{"1440x240@60Hz 4:3", 60, 15734, 27000},
	{"1440x240@60Hz 16:9", 60, 15734, 27000},
	{"2880x480i@60Hz 4:3", 60, 15734, 54000},
	/* VIC 11 */
	{"2880x480i@60Hz 16:9", 60, 15734, 54000},
	{"2880x240@60Hz 4:3", 60, 15734, 54000},
	{"2880x240@60Hz 16:9", 60, 15734, 54000},
	{"1440x480@60Hz 4:3", 60, 31469, 54000},
	{"1440x480@60Hz 16:9", 60, 31469, 54000},
	{"1920x1080@60Hz 16:9", 60, 67500, 148500},
	{"720x576@50Hz 4:3", 50, 31250, 27000},
	{"720x576@50Hz 16:9", 50, 31250, 27000},
	{"1280x720@50Hz 16:9", 50, 37500, 74250},
	{"1920x1080i@50Hz 16:9", 50, 28125, 74250},
	/* VIC 21 */
	{"1440x576i@50Hz 4:3", 50, 15625, 27000},
	{"1440x576i@50Hz 16:9", 50, 15625, 27000},
	{"1440x288@50Hz 4:3", 50, 15625, 27000},
	{"1440x288@50Hz 16:9", 50, 15625, 27000},
	{"2880x576i@50Hz 4:3", 50, 15625, 54000},
	{"2880x576i@50Hz 16:9", 50, 15625, 54000},
	{"2880x288@50Hz 4:3", 50, 15625, 54000},
	{"2880x288@50Hz 16:9", 50, 15625, 54000},
	{"1440x576@50Hz 4:3", 50, 31250, 54000},
	{"1440x576@50Hz 16:9", 50, 31250, 54000},
	/* VIC 31 */
	{"1920x1080@50Hz 16:9", 50, 56250, 148500},
	{"1920x1080@24Hz 16:9", 24, 27000, 74250},
	{"1920x1080@25Hz 16:9", 25, 28125, 74250},
	{"1920x1080@30Hz 16:9", 30, 33750, 74250},
	{"2880x480@60Hz 4:3", 60, 31469, 108000},
	{"2880x480@60Hz 16:9", 60, 31469, 108000},
	{"2880x576@50Hz 4:3", 50, 31250, 108000},
	{"2880x576@50Hz 16:9", 50, 31250, 108000},
	{"1920x1080i@50Hz 16:9", 50, 31250, 72000},
	{"1920x1080i@100Hz 16:9", 100, 56250, 148500},
	/* VIC 41 */
	{"1280x720@100Hz 16:9", 100, 75000, 148500},
	{"720x576@100Hz 4:3", 100, 62500, 54000},
	{"720x576@100Hz 16:9", 100, 62500, 54000},
	{"1440x576@100Hz 4:3", 100, 31250, 54000},
	{"1440x576@100Hz 16:9", 100, 31250, 54000},
	{"1920x1080i@120Hz 16:9", 120, 67500, 148500},
	{"1280x720@120Hz 16:9", 120, 90000, 148500},
	{"720x480@120Hz 4:3", 120, 62937, 54000},
	{"720x480@120Hz 16:9", 120, 62937, 54000},
	{"1440x480i@120Hz 4:3", 120, 31469, 54000},
	/* VIC 51 */
	{"1440x480i@120Hz 16:9", 120, 31469, 54000},
	{"720x576@200Hz 4:3", 200, 125000, 108000},
	{"720x576@200Hz 16:9", 200, 125000, 108000},
	{"1440x576i@200Hz 4:3", 200, 62500, 108000},
	{"1440x576i@200Hz 16:9", 200, 62500, 108000},
	{"720x480@240Hz 4:3", 240, 125874, 108000},
	{"720x480@240Hz 16:9", 240, 125874, 108000},
	{"1440x480i@240Hz 4:3", 240, 62937, 108000},
	{"1440x480i@240Hz 16:9", 240, 62937, 108000},
	{"1280x720@24Hz 16:9", 24, 18000, 59400},
	/* VIC 61 */
	{"1280x720@25Hz 16:9", 25, 18750, 74250},
	{"1280x720@30Hz 16:9", 30, 22500, 74250},
	{"1920x1080@120Hz 16:9", 120, 135000, 297000},
	{"1920x1080@100Hz 16:9", 100, 112500, 297000},
	{"1280x720@24Hz 64:27", 24, 18000, 59400},
	{"1280x720@25Hz 64:27", 25, 18750, 74250},
	{"1280x720@30Hz 64:27", 30, 22500, 74250},
	{"1280x720@50Hz 64:27", 50, 37500, 74250},
	{"1280x720@60Hz 64:27", 60, 45000, 74250},
	{"1280x720@100Hz 64:27", 100, 75000, 148500},
	/* VIC 71 */
	{"1280x720@120Hz 64:27", 120, 91000, 148500},
	{"1920x1080@24Hz 64:27", 24, 27000, 74250},
	{"1920x1080@25Hz 64:27", 25, 28125, 74250},
	{"1920x1080@30Hz 64:27", 30, 33750, 74250},
	{"1920x1080@50Hz 64:27", 50, 56250, 148500},
	{"1920x1080@60Hz 64:27", 60, 67500, 148500},
	{"1920x1080@100Hz 64:27", 100, 112500, 297000},
	{"1920x1080@120Hz 64:27", 120, 135000, 297000},
	{"1680x720@24Hz 64:27", 24, 18000, 59400},
	{"1680x720@25Hz 64:27", 25, 18750, 59400},
	/* VIC 81 */
	{"1680x720@30Hz 64:27", 30, 22500, 59400},
	{"1680x720@50Hz 64:27", 50, 37500, 82500},
	{"1680x720@60Hz 64:27", 60, 45000, 99000},
	{"1680x720@100Hz 64:27", 100, 82500, 165000},
	{"1680x720@120Hz 64:27", 120, 99000, 198000},
	{"2560x1080@24Hz 64:27", 24, 26400, 99000},
	{"2560x1080@25Hz 64:27", 25, 28125, 90000},
	{"2560x1080@30Hz 64:27", 30, 33750, 118800},
	{"2560x1080@50Hz 64:27", 50, 56250, 185625},
	{"2560x1080@60Hz 64:27", 60, 66000, 198000},
	/* VIC 91 */
	{"2560x1080@100Hz 64:27", 100, 125000, 371250},
	{"2560x1080@120Hz 64:27", 120, 150000, 495000},
	{"3840x2160@24Hz 16:9", 24, 54000, 297000},
	{"3840x2160@25Hz 16:9", 25, 56250, 297000},
	{"3840x2160@30Hz 16:9", 30, 67500, 297000},
	{"3840x2160@50Hz 16:9", 50, 112500, 594000},
	{"3840x2160@60Hz 16:9", 60, 135000, 594000},
	{"4096x2160@24Hz 256:135", 24, 54000, 297000},
	{"4096x2160@25Hz 256:135", 25, 56250, 297000},
	{"4096x2160@30Hz 256:135", 30, 67500, 297000},
	/* VIC 101 */
	{"4096x2160@50Hz 256:135", 50, 112500, 594000},
	{"4096x2160@60Hz 256:135", 60, 135000, 594000},
	{"3840x2160@24Hz 64:27", 24, 54000, 297000},
	{"3840x2160@25Hz 64:27", 25, 56250, 297000},
	{"3840x2160@30Hz 64:27", 30, 67500, 297000},
	{"3840x2160@50Hz 64:27", 50, 112500, 594000},
	{"3840x2160@60Hz 64:27", 60, 135000, 594000},
	{"1280x720@48Hz 16:9", 48, 36000, 90000},
	{"1280x720@48Hz 64:27", 48, 36000, 90000},
	{"1680x720@48Hz 64:27", 48, 36000, 99000},
	/* VIC 111 */
	{"1920x1080@48Hz 16:9", 48, 54000, 148500},
	{"1920x1080@48Hz 64:27", 48, 54000, 148500},
	{"2560x1080@48Hz 64:27", 48, 52800, 198000},
	{"3840x2160@48Hz 16:9", 48, 108000, 594000},
	{"4096x2160@48Hz 256:135", 48, 108000, 594000},
	{"3840x2160@48Hz 64:27", 48, 108000, 594000},
	{"3840x2160@100Hz 16:9", 100, 225000, 1188000},
	{"3840x2160@120Hz 16:9", 120, 270000, 1188000},
	{"3840x2160@100Hz 64:27", 100, 225000, 1188000},
	{"3840x2160@120Hz 64:27", 120, 270000, 1188000},
	/* VIC 121 */
	{"5120x2160@24Hz 64:27", 24, 52800, 396000},
	{"5120x2160@25Hz 64:27", 25, 55000, 396000},
	{"5120x2160@30Hz 64:27", 30, 66000, 396000},
	{"5120x2160@48Hz 64:27", 48, 118800, 742500},
	{"5120x2160@50Hz 64:27", 50, 112500, 742500},
	{"5120x2160@60Hz 64:27", 60, 135000, 742500},
	{"5120x2160@100Hz 64:27", 100, 225000, 1485000},
};

static struct edid_cta_mode edid_cta_modes2[] = {
	/* VIC 193 */
	{"5120x2160@120Hz 64:27", 120, 270000, 1485000},
	{"7680x4320@24Hz 16:9", 24, 108000, 1188000},
	{"7680x4320@25Hz 16:9", 25, 110000, 1188000},
	{"7680x4320@30Hz 16:9", 30, 132000, 1188000},
	{"7680x4320@48Hz 16:9", 48, 216000, 2376000},
	{"7680x4320@50Hz 16:9", 50, 220000, 2376000},
	{"7680x4320@60Hz 16:9", 60, 264000, 2376000},
	{"7680x4320@100Hz 16:9", 100, 450000, 4752000},
	/* VIC 201 */
	{"7680x4320@120Hz 16:9", 120, 540000, 4752000},
	{"7680x4320@24Hz 64:27", 24, 108000, 1188000},
	{"7680x4320@25Hz 64:27", 25, 110000, 1188000},
	{"7680x4320@30Hz 64:27", 30, 132000, 1188000},
	{"7680x4320@48Hz 64:27", 48, 216000, 2376000},
	{"7680x4320@50Hz 64:27", 50, 220000, 2376000},
	{"7680x4320@60Hz 64:27", 60, 264000, 2376000},
	{"7680x4320@100Hz 64:27", 100, 450000, 4752000},
	{"7680x4320@120Hz 64:27", 120, 540000, 4752000},
	{"10240x4320@24Hz 64:27", 24, 118800, 1485000},
	/* VIC 211 */
	{"10240x4320@25Hz 64:27", 25, 110000, 1485000},
	{"10240x4320@30Hz 64:27", 30, 135000, 1485000},
	{"10240x4320@48Hz 64:27", 48, 237600, 2970000},
	{"10240x4320@50Hz 64:27", 50, 220000, 2970000},
	{"10240x4320@60Hz 64:27", 60, 270000, 2970000},
	{"10240x4320@100Hz 64:27", 100, 450000, 5940000},
	{"10240x4320@120Hz 64:27", 120, 540000, 5940000},
	{"4096x2160@100Hz 256:135", 100, 225000, 1188000},
	{"4096x2160@120Hz 256:135", 120, 270000, 1188000},
};

static const struct edid_cta_mode *vic_to_mode(unsigned char vic)
{
	if (vic > 0 && vic <= ARRAY_SIZE(edid_cta_modes1))
		return edid_cta_modes1 + vic - 1;
	if (vic >= 193 && vic <= ARRAY_SIZE(edid_cta_modes2) + 193)
		return edid_cta_modes2 + vic - 193;
	return NULL;
}

static void cta_svd(const unsigned char *x, int n, int for_ycbcr420)
{
	int i;

	for (i = 0; i < n; i++)  {
		const struct edid_cta_mode *vicmode = NULL;
		unsigned char svd = x[i];
		unsigned char native;
		unsigned char vic;
		const char *mode;
		unsigned hfreq = 0;
		unsigned clock_khz = 0;

		if ((svd & 0x7f) == 0)
			continue;

		if ((svd - 1) & 0x40) {
			vic = svd;
			native = 0;
		} else {
			vic = svd & 0x7f;
			native = svd & 0x80;
		}

		vicmode = vic_to_mode(vic);
		if (vicmode) {
			switch (vic) {
			case 95:
				supported_hdmi_vic_vsb_codes |= 1 << 0;
				break;
			case 94:
				supported_hdmi_vic_vsb_codes |= 1 << 1;
				break;
			case 93:
				supported_hdmi_vic_vsb_codes |= 1 << 2;
				break;
			case 98:
				supported_hdmi_vic_vsb_codes |= 1 << 3;
				break;
			}
			mode = vicmode->name;
			min_vert_freq_hz = min(min_vert_freq_hz, vicmode->refresh);
			max_vert_freq_hz = max(max_vert_freq_hz, vicmode->refresh);
			hfreq = vicmode->hor_freq_hz;
			min_hor_freq_hz = min(min_hor_freq_hz, hfreq);
			max_hor_freq_hz = max(max_hor_freq_hz, hfreq);
			clock_khz = vicmode->pixclk_khz / (for_ycbcr420 ? 2 : 1);
			max_pixclk_khz = max(max_pixclk_khz, clock_khz);
		} else {
			mode = "Unknown mode";
		}

		printf("    VIC %3d %s %s HorFreq: %d Hz Clock: %.3f MHz\n",
		       vic, mode, native ? "(native)" : "", hfreq, clock_khz / 1000.0);
		if (vic == 1)
			has_cta861_vic_1 = 1;
	}
}

static void cta_video_block(const unsigned char *x, unsigned int length)
{
	cta_svd(x, length, 0);
}

static void cta_y420vdb(const unsigned char *x, unsigned int length)
{
	cta_svd(x, length, 1);
}

static void cta_y420cmdb(const unsigned char *x, unsigned int length)
{
	int i;

	for (i = 0; i < length; i++) {
		uint8_t v = x[0 + i];
		int j;

		for (j = 0; j < 8; j++)
			if (v & (1 << j))
				printf("    VSD Index %d\n", i * 8 + j);
	}
}

static void cta_vfpdb(const unsigned char *x, unsigned int length)
{
	int i;

	for (i = 0; i < length; i++)  {
		unsigned char svr = x[i];

		if ((svr > 0 && svr < 128) || (svr > 192 && svr < 254)) {
			const struct edid_cta_mode *vicmode;
			unsigned char vic;
			const char *mode;

			vic = svr;

			vicmode = vic_to_mode(vic);
			if (vicmode)
				mode = vicmode->name;
			else
				mode = "Unknown mode";

			printf("    VIC %02d %s\n", vic, mode);

		} else if (svr > 128 && svr < 145) {
			printf("    DTD number %02d\n", svr - 128);
		}
	}
}

static struct {
	const char *name;
	int refresh, hor_freq_hz, pixclk_khz;
} edid_hdmi_modes[] = {
	{"3840x2160@30Hz 16:9", 30, 67500, 297000},
	{"3840x2160@25Hz 16:9", 25, 56250, 297000},
	{"3840x2160@24Hz 16:9", 24, 54000, 297000},
	{"4096x2160@24Hz 256:135", 24, 54000, 297000},
};

static void cta_hdmi_block(const unsigned char *x, unsigned int length)
{
	int mask = 0, formats = 0;
	int len_vic, len_3d;
	int b = 0;

	printf(" (HDMI)\n");
	printf("    Source physical address %d.%d.%d.%d\n", x[3] >> 4, x[3] & 0x0f,
	       x[4] >> 4, x[4] & 0x0f);

	if (length < 6)
		return;

	if (x[5] & 0x80)
		printf("    Supports_AI\n");
	if (x[5] & 0x40)
		printf("    DC_48bit\n");
	if (x[5] & 0x20)
		printf("    DC_36bit\n");
	if (x[5] & 0x10)
		printf("    DC_30bit\n");
	if (x[5] & 0x08)
		printf("    DC_Y444\n");
	/* two reserved */
	if (x[5] & 0x01)
		printf("    DVI_Dual\n");

	if (length < 7)
		return;

	printf("    Maximum TMDS clock: %dMHz\n", x[6] * 5);
	if (x[6] * 5 > 340)
		nonconformant_hdmi_vsdb_tmds_rate = 1;

	/* XXX the walk here is really ugly, and needs to be length-checked */
	if (length < 8)
		return;

	if (x[7] & 0x0f) {
		printf("    Supported Content Types:\n");
		if (x[7] & 0x01)
			printf("      Graphics\n");
		if (x[7] & 0x02)
			printf("      Photo\n");
		if (x[7] & 0x04)
			printf("      Cinema\n");
		if (x[7] & 0x08)
			printf("      Game\n");
	}

	if (x[7] & 0x80) {
		printf("    Video latency: %d\n", x[8 + b]);
		printf("    Audio latency: %d\n", x[9 + b]);
		b += 2;

		if (x[7] & 0x40) {
			printf("    Interlaced video latency: %d\n", x[8 + b]);
			printf("    Interlaced audio latency: %d\n", x[9 + b]);
			b += 2;
		}
	}

	if (!(x[7] & 0x20))
		return;

	printf("    Extended HDMI video details:\n");
	if (x[8 + b] & 0x80)
		printf("      3D present\n");
	if ((x[8 + b] & 0x60) == 0x20) {
		printf("      All advertised VICs are 3D-capable\n");
		formats = 1;
	}
	if ((x[8 + b] & 0x60) == 0x40) {
		printf("      3D-capable-VIC mask present\n");
		formats = 1;
		mask = 1;
	}
	switch (x[8 + b] & 0x18) {
	case 0x00: break;
	case 0x08:
		   printf("      Base EDID image size is aspect ratio\n");
		   break;
	case 0x10:
		   printf("      Base EDID image size is in units of 1cm\n");
		   break;
	case 0x18:
		   printf("      Base EDID image size is in units of 5cm\n");
		   break;
	}
	len_vic = (x[9 + b] & 0xe0) >> 5;
	len_3d = (x[9 + b] & 0x1f) >> 0;
	b += 2;

	if (len_vic) {
		unsigned hfreq = 0;
		unsigned clock_khz = 0;
		int i;

		for (i = 0; i < len_vic; i++) {
			unsigned char vic = x[8 + b + i];
			const char *mode;

			if (vic && vic <= ARRAY_SIZE(edid_hdmi_modes)) {
				supported_hdmi_vic_codes |= 1 << (vic - 1);
				mode = edid_hdmi_modes[vic - 1].name;
				min_vert_freq_hz = min(min_vert_freq_hz, edid_hdmi_modes[vic - 1].refresh);
				max_vert_freq_hz = max(max_vert_freq_hz, edid_hdmi_modes[vic - 1].refresh);
				hfreq = edid_hdmi_modes[vic - 1].hor_freq_hz;
				min_hor_freq_hz = min(min_hor_freq_hz, hfreq);
				max_hor_freq_hz = max(max_hor_freq_hz, hfreq);
				clock_khz = edid_hdmi_modes[vic - 1].pixclk_khz;
				max_pixclk_khz = max(max_pixclk_khz, clock_khz);
			} else {
				mode = "Unknown mode";
			}

			printf("      HDMI VIC %d %s HorFreq: %d Hz Clock: %.3f MHz\n",
			       vic, mode, hfreq, clock_khz / 1000.0);
		}

		b += len_vic;
	}

	if (len_3d) {
		if (formats) {
			/* 3D_Structure_ALL_15..8 */
			if (x[8 + b] & 0x80)
				printf("      3D: Side-by-side (half, quincunx)\n");
			if (x[8 + b] & 0x01)
				printf("      3D: Side-by-side (half, horizontal)\n");
			/* 3D_Structure_ALL_7..0 */
			if (x[9 + b] & 0x40)
				printf("      3D: Top-and-bottom\n");
			if (x[9 + b] & 0x20)
				printf("      3D: L + depth + gfx + gfx-depth\n");
			if (x[9 + b] & 0x10)
				printf("      3D: L + depth\n");
			if (x[9 + b] & 0x08)
				printf("      3D: Side-by-side (full)\n");
			if (x[9 + b] & 0x04)
				printf("      3D: Line-alternative\n");
			if (x[9 + b] & 0x02)
				printf("      3D: Field-alternative\n");
			if (x[9 + b] & 0x01)
				printf("      3D: Frame-packing\n");
			b += 2;
			len_3d -= 2;
		}
		if (mask) {
			int i;
			printf("      3D VIC indices:");
			/* worst bit ordering ever */
			for (i = 0; i < 8; i++)
				if (x[9 + b] & (1 << i))
					printf(" %d", i);
			for (i = 0; i < 8; i++)
				if (x[8 + b] & (1 << i))
					printf(" %d", i + 8);
			printf("\n");
			b += 2;
			len_3d -= 2;
		}

		/*
		 * list of nibbles:
		 * 2D_VIC_Order_X
		 * 3D_Structure_X
		 * (optionally: 3D_Detail_X and reserved)
		 */
		if (len_3d > 0) {
			int end = b + len_3d;

			while (b < end) {
				printf("      VIC index %d supports ", x[8 + b] >> 4);
				switch (x[8 + b] & 0x0f) {
				case 0: printf("frame packing"); break;
				case 6: printf("top-and-bottom"); break;
				case 8:
					if ((x[9 + b] >> 4) == 1) {
						printf("side-by-side (half, horizontal)");
						break;
					}
				default: printf("unknown");
				}
				printf("\n");

				if ((x[8 + b] & 0x0f) > 7) {
					/* Optional 3D_Detail_X and reserved */
					b++;
				}
				b++;
			}
		}
	}
}

static const char *max_frl_rates[] = {
	"Not Supported",
	"3 Gbps per lane on 3 lanes",
	"3 and 6 Gbps per lane on 3 lanes",
	"3 and 6 Gbps per lane on 3 lanes, 6 Gbps on 4 lanes",
	"3 and 6 Gbps per lane on 3 lanes, 6 and 8 Gbps on 4 lanes",
	"3 and 6 Gbps per lane on 3 lanes, 6, 8 and 10 Gbps on 4 lanes",
	"3 and 6 Gbps per lane on 3 lanes, 6, 8, 10 and 12 Gbps on 4 lanes",
};

static const char *dsc_max_slices[] = {
	"Not Supported",
	"up to 1 slice and up to (340 MHz/Ksliceadjust) pixel clock per slice",
	"up to 2 slices and up to (340 MHz/Ksliceadjust) pixel clock per slice",
	"up to 4 slices and up to (340 MHz/Ksliceadjust) pixel clock per slice",
	"up to 8 slices and up to (340 MHz/Ksliceadjust) pixel clock per slice",
	"up to 8 slices and up to (400 MHz/Ksliceadjust) pixel clock per slice",
	"up to 12 slices and up to (400 MHz/Ksliceadjust) pixel clock per slice",
	"up to 16 slices and up to (400 MHz/Ksliceadjust) pixel clock per slice",
};

static void cta_hf_block(const unsigned char *x, unsigned int length)
{
	unsigned rate = x[4] * 5;

	printf(" (HDMI Forum)\n");
	printf("    Version: %u\n", x[3]);
	if (rate) {
		printf("    Maximum TMDS Character Rate: %uMHz\n", rate);
		if ((rate && rate <= 340) || rate > 600)
			nonconformant_hf_vsdb_tmds_rate = 1;
	}
	if (x[5] & 0x80)
		printf("    SCDC Present\n");
	if (x[5] & 0x40)
		printf("    SCDC Read Request Capable\n");
	if (x[5] & 0x10)
		printf("    Supports Color Content Bits Per Component Indication\n");
	if (x[5] & 0x08)
		printf("    Supports scrambling for <= 340 Mcsc\n");
	if (x[5] & 0x04)
		printf("    Supports 3D Independent View signaling\n");
	if (x[5] & 0x02)
		printf("    Supports 3D Dual View signaling\n");
	if (x[5] & 0x01)
		printf("    Supports 3D OSD Disparity signaling\n");
	if (x[6] & 0xf0) {
		unsigned max_frl_rate = x[6] >> 4;

		printf("    Max Fix Rate Link: ");
		if (max_frl_rate >= ARRAY_SIZE(max_frl_rates))
			printf("Reserved\n");
		else
			printf("%s\n", max_frl_rates[max_frl_rate]);
		if (max_frl_rate == 1 && rate < 300)
			nonconformant_hf_vsdb_tmds_rate = 1;
		else if (max_frl_rate >= 2 && rate < 600)
			nonconformant_hf_vsdb_tmds_rate = 1;
	}
	if (x[6] & 0x04)
		printf("    Supports 16-bits/component Deep Color 4:2:0 Pixel Encoding\n");
	if (x[6] & 0x02)
		printf("    Supports 12-bits/component Deep Color 4:2:0 Pixel Encoding\n");
	if (x[6] & 0x01)
		printf("    Supports 10-bits/component Deep Color 4:2:0 Pixel Encoding\n");

	if (length <= 7)
		return;

	if (x[7] & 0x20)
		printf("    Supports Mdelta\n");
	if (x[7] & 0x10)
		printf("    Supports media rates below VRRmin (CinemaVRR)\n");
	if (x[7] & 0x08)
		printf("    Supports negative Mvrr values\n");
	if (x[7] & 0x04)
		printf("    Supports Fast Vactive\n");
	if (x[7] & 0x02)
		printf("    Supports Auto Low-Latency Mode\n");
	if (x[7] & 0x01)
		printf("    Supports a FAPA in blanking after first active video line\n");

	if (length <= 8)
		return;

	printf("    VRRmin: %d\n", x[8] & 0x3f);
	printf("    VRRmax: %d\n", (x[8] & 0xc0) << 2 | x[9]);

	if (length <= 10)
		return;

	if (x[10] & 0x80)
		printf("    Supports VESA DSC 1.2a compression\n");
	if (x[10] & 0x40)
		printf("    Supports Compressed Video Transport for 4:2:0 Pixel Encoding\n");
	if (x[10] & 0x08)
		printf("    Supports Compressed Video Transport at any valid 1/16th bit bpp\n");
	if (x[10] & 0x04)
		printf("    Supports 16 bpc Compressed Video Transport\n");
	if (x[10] & 0x02)
		printf("    Supports 12 bpc Compressed Video Transport\n");
	if (x[10] & 0x01)
		printf("    Supports 10 bpc Compressed Video Transport\n");
	if (x[11] & 0xf) {
		unsigned max_slices = x[11] & 0xf;

		if (max_slices < ARRAY_SIZE(dsc_max_slices))
			printf("    Supports %s\n", dsc_max_slices[max_slices]);
	}
	if (x[11] & 0xf0) {
		unsigned max_frl_rate = x[11] >> 4;

		printf("    DSC Max Fix Rate Link: ");
		if (max_frl_rate >= ARRAY_SIZE(max_frl_rates))
			printf("Reserved\n");
		else
			printf("%s\n", max_frl_rates[max_frl_rate]);
	}
	if (x[12] & 0x3f)
		printf("    Maximum number of bytes in a line of chunks: %u\n",
		       1024 * (1 + (x[12] & 0x3f)));
}

DEFINE_FIELD("YCbCr quantization", YCbCr_quantization, 7, 7,
	     { 0, "No Data" },
	     { 1, "Selectable (via AVI YQ)" });
DEFINE_FIELD("RGB quantization", RGB_quantization, 6, 6,
	     { 0, "No Data" },
	     { 1, "Selectable (via AVI Q)" });
DEFINE_FIELD("PT scan behaviour", PT_scan, 4, 5,
	     { 0, "No Data" },
	     { 1, "Always Overscannned" },
	     { 2, "Always Underscanned" },
	     { 3, "Support both over- and underscan" });
DEFINE_FIELD("IT scan behaviour", IT_scan, 2, 3,
	     { 0, "IT video formats not supported" },
	     { 1, "Always Overscannned" },
	     { 2, "Always Underscanned" },
	     { 3, "Support both over- and underscan" });
DEFINE_FIELD("CE scan behaviour", CE_scan, 0, 1,
	     { 0, "CE video formats not supported" },
	     { 1, "Always Overscannned" },
	     { 2, "Always Underscanned" },
	     { 3, "Support both over- and underscan" });

static struct field *vcdb_fields[] = {
	&YCbCr_quantization,
	&RGB_quantization,
	&PT_scan,
	&IT_scan,
	&CE_scan,
};

static const char *speaker_map[] = {
	"FL/FR - Front Left/Right",
	"LFE - Low Frequency Effects",
	"FC - Front Center",
	"BL/BR - Back Left/Right",
	"BC - Back Center",
	"FLC/FRC - Front Left/Right of Center",
	"RLC/RRC - Rear Left/Right of Center",
	"FLW/FRW - Front Left/Right Wide",
	"TpFL/TpFR - Top Front Left/Right",
	"TpC - Top Center",
	"TpFC - Top Front Center",
	"LS/RS - Left/Right Surround",
	"LFE2 - Low Frequency Effects 2",
	"TpBC - Top Back Center",
	"SiL/SiR - Side Left/Right",
	"TpSiL/TpSiR - Top Side Left/Right",
	"TpBL/TpBR - Top Back Left/Right",
	"BtFC - Bottom Front Center",
	"BtFL/BtBR - Bottom Front Left/Right",
	"TpLS/TpRS - Top Left/Right Surround",
	"LSd/RSd - Left/Right Surround Direct",
};

static void cta_sadb(const unsigned char *x, unsigned int length)
{
	uint32_t sad;
	int i;

	if (length < 3)
		return;

	sad = ((x[2] << 16) | (x[1] << 8) | x[0]);

	printf("    Speaker map:\n");

	for (i = 0; i < ARRAY_SIZE(speaker_map); i++) {
		if ((sad >> i) & 1)
			printf("      %s\n", speaker_map[i]);
	}
}

static float decode_uchar_as_float(unsigned char x)
{
	signed char s = (signed char)x;

	return s / 64.0;
}

static void cta_rcdb(const unsigned char *x, unsigned int length)
{
	uint32_t spm = ((x[3] << 16) | (x[2] << 8) | x[1]);
	int i;

	if (length < 4)
		return;

	if (x[0] & 0x40)
		printf("    Speaker count: %d\n", (x[0] & 0x1f) + 1);

	printf("    Speaker Presence Mask:\n");
	for (i = 0; i < ARRAY_SIZE(speaker_map); i++) {
		if ((spm >> i) & 1)
			printf("      %s\n", speaker_map[i]);
	}
	if ((x[0] & 0x20) && length >= 7) {
		printf("    Xmax: %d dm\n", x[4]);
		printf("    Ymax: %d dm\n", x[5]);
		printf("    Zmax: %d dm\n", x[6]);
	}
	if ((x[0] & 0x80) && length >= 10) {
		printf("    DisplayX: %.3f * Xmax\n", decode_uchar_as_float(x[7]));
		printf("    DisplayY: %.3f * Ymax\n", decode_uchar_as_float(x[8]));
		printf("    DisplayZ: %.3f * Zmax\n", decode_uchar_as_float(x[9]));
	}
}

static const char *speaker_location[] = {
	"FL - Front Left",
	"FR - Front Right",
	"FC - Front Center",
	"LFE1 - Low Frequency Effects 1",
	"BL - Back Left",
	"BR - Back Right",
	"FLC - Front Left of Center",
	"FRC - Front Right of Center",
	"BC - Back Center",
	"LFE2 - Low Frequency Effects 2",
	"SiL - Side Left",
	"SiR - Side Right",
	"TpFL - Top Front Left",
	"TpFR - Top Front Right",
	"TpFC - Top Front Center",
	"TpC - Top Center",
	"TpBL - Top Back Left",
	"TpBR - Top Back Right",
	"TpSiL - Top Side Left",
	"TpSiR - Top Side Right",
	"TpBC - Top Back Center",
	"BtFC - Bottom Front Center",
	"BtFL - Bottom Front Left",
	"BtBR - Bottom Front Right",
	"FLW - Front Left Wide",
	"FRW - Front Right Wide",
	"LS - Left Surround",
	"RS - Right Surround",
};

static void cta_sldb(const unsigned char *x, unsigned int length)
{
	while (length >= 2) {
		printf("    Channel: %d (%sactive)\n", x[0] & 0x1f,
		       (x[0] & 0x20) ? "" : "not ");
		if ((x[1] & 0x1f) < ARRAY_SIZE(speaker_location))
			printf("      Speaker: %s\n", speaker_location[x[1] & 0x1f]);
		if (length >= 5 && (x[0] & 0x40)) {
			printf("      X: %.3f * Xmax\n", decode_uchar_as_float(x[2]));
			printf("      Y: %.3f * Ymax\n", decode_uchar_as_float(x[3]));
			printf("      Z: %.3f * Zmax\n", decode_uchar_as_float(x[4]));
			length -= 3;
			x += 3;
		}

		length -= 2;
		x += 2;
	}
}

static void cta_vcdb(const unsigned char *x, unsigned int length)
{
	unsigned char d = x[0];

	decode(vcdb_fields, d, "    ");
}

static const char *colorimetry_map[] = {
	"xvYCC601",
	"xvYCC709",
	"sYCC601",
	"AdobeYCC601",
	"AdobeRGB",
	"BT2020cYCC",
	"BT2020YCC",
	"BT2020RGB",
};

static void cta_colorimetry_block(const unsigned char *x, unsigned int length)
{
	int i;

	if (length >= 2) {
		for (i = 0; i < ARRAY_SIZE(colorimetry_map); i++) {
			if (x[0] & (1 << i))
				printf("    %s\n", colorimetry_map[i]);
		}
		if (x[1] & 0x80)
			printf("    DCI-P3\n");
	}
}

static const char *eotf_map[] = {
	"Traditional gamma - SDR luminance range",
	"Traditional gamma - HDR luminance range",
	"SMPTE ST2084",
	"Hybrid Log-Gamma",
};

static void cta_hdr_static_metadata_block(const unsigned char *x, unsigned int length)
{
	int i;

	if (length >= 2) {
		printf("    Electro optical transfer functions:\n");
		for (i = 0; i < 6; i++) {
			if (x[0] & (1 << i)) {
				printf("      %s\n", i < ARRAY_SIZE(eotf_map) ?
				       eotf_map[i] : "Unknown");
			}
		}
		printf("    Supported static metadata descriptors:\n");
		for (i = 0; i < 8; i++) {
			if (x[1] & (1 << i))
				printf("      Static metadata type %d\n", i + 1);
		}
	}

	if (length >= 3)
		printf("    Desired content max luminance: %d (%.3f cd/m^2)\n",
		       x[2], 50.0 * pow(2, x[2] / 32.0));

	if (length >= 4)
		printf("    Desired content max frame-average luminance: %d (%.3f cd/m^2)\n",
		       x[3], 50.0 * pow(2, x[3] / 32.0));

	if (length >= 5)
		printf("    Desired content min luminance: %d (%.3f cd/m^2)\n",
		       x[4], (50.0 * pow(2, x[2] / 32.0)) * pow(x[4] / 255.0, 2) / 100.0);
}

static void cta_hdr_dyn_metadata_block(const unsigned char *x, unsigned int length)
{
	while (length >= 3) {
		int type_len = x[0];
		int type = x[1] | (x[2] << 8);

		if (length < type_len + 1)
			return;
		printf("    HDR Dynamic Metadata Type %d\n", type);
		switch (type) {
		case 1:
		case 2:
		case 4:
			if (type_len > 2)
				printf("      Version: %d\n", x[3] & 0xf);
			break;
		default:
			break;
		}
		length -= type_len + 1;
		x += type_len + 1;
	}
}

static void cta_ifdb(const unsigned char *x, unsigned int length)
{
	int len_hdr = x[0] >> 5;

	if (length < 2)
		return;
	printf("    VSIFs: %d\n", x[1]);
	if (length < len_hdr + 2)
		return;
	length -= len_hdr + 2;
	x += len_hdr + 2;
	while (length > 0) {
		int payload_len = x[0] >> 5;

		if ((x[0] & 0x1f) == 1 && length >= 4) {
			printf("    InfoFrame Type Code %d IEEE OUI: %02x%02x%02x\n",
			       x[0] & 0x1f, x[3], x[2], x[1]);
			x += 4;
			length -= 4;
		} else {
			printf("    InfoFrame Type Code %d\n", x[0] & 0x1f);
			x++;
			length--;
		}
		x += payload_len;
		length -= payload_len;
	}
}

static void cta_hdmi_audio_block(const unsigned char *x, unsigned int length)
{
	int num_descs;

	if (length < 2)
		return;
	if (x[0] & 3)
		printf("    Max Stream Count: %d\n", (x[0] & 3) + 1);
	if (x[0] & 4)
		printf("    Supports MS NonMixed\n");

	num_descs = x[1] & 7;
	if (num_descs == 0)
		return;
	length -= 2;
	x += 2;
	while (length >= 4) {
		if (length > 4) {
			int format = x[0] & 0xf;

			printf("    %s, max channels %d\n", audio_format(format),
			       (x[1] & 0x1f)+1);
			printf("      Supported sample rates (kHz):%s%s%s%s%s%s%s\n",
			       (x[2] & 0x40) ? " 192" : "",
			       (x[2] & 0x20) ? " 176.4" : "",
			       (x[2] & 0x10) ? " 96" : "",
			       (x[2] & 0x08) ? " 88.2" : "",
			       (x[2] & 0x04) ? " 48" : "",
			       (x[2] & 0x02) ? " 44.1" : "",
			       (x[2] & 0x01) ? " 32" : "");
			if (format == 1)
				printf("      Supported sample sizes (bits):%s%s%s\n",
				       (x[3] & 0x04) ? " 24" : "",
				       (x[3] & 0x02) ? " 20" : "",
				       (x[3] & 0x01) ? " 16" : "");
		} else {
			uint32_t sad = ((x[2] << 16) | (x[1] << 8) | x[0]);
			int i;

			switch (x[3] >> 4) {
			case 1:
				printf("    Speaker Allocation for 10.2 channels:\n");
				break;
			case 2:
				printf("    Speaker Allocation for 22.2 channels:\n");
				break;
			case 3:
				printf("    Speaker Allocation for 30.2 channels:\n");
				break;
			default:
				printf("    Unknown Speaker Allocation (%d)\n", x[3] >> 4);
				return;
			}

			for (i = 0; i < ARRAY_SIZE(speaker_map); i++) {
				if ((sad >> i) & 1)
					printf("      %s\n", speaker_map[i]);
			}
		}
		length -= 4;
		x += 4;
	}
}

static void cta_block(const unsigned char *x)
{
	static int last_block_was_hdmi_vsdb;
	unsigned int length = x[0] & 0x1f;
	unsigned int oui;

	switch ((x[0] & 0xe0) >> 5) {
	case 0x01:
		printf("  Audio data block\n");
		cta_audio_block(x + 1, length);
		break;
	case 0x02:
		printf("  Video data block\n");
		cta_video_block(x + 1, length);
		break;
	case 0x03:
		/* yes really, endianness lols */
		oui = (x[3] << 16) + (x[2] << 8) + x[1];
		printf("  Vendor-specific data block, OUI %06x", oui);
		if (oui == 0x000c03) {
			cta_hdmi_block(x + 1, length);
			last_block_was_hdmi_vsdb = 1;
			return;
		}
		if (oui == 0xc45dd8) {
			if (!last_block_was_hdmi_vsdb)
				nonconformant_hf_vsdb_position = 1;
			cta_hf_block(x + 1, length);
		} else {
			printf("\n");
		}
		break;
	case 0x04:
		printf("  Speaker allocation data block\n");
		cta_sadb(x + 1, length);
		break;
	case 0x05:
		printf("  VESA DTC data block\n");
		break;
	case 0x07:
		printf("  Extended tag: ");
		switch (x[1]) {
		case 0x00:
			printf("Video capability data block\n");
			cta_vcdb(x + 2, length - 1);
			break;
		case 0x01:
			printf("Vendor-specific video data block\n");
			break;
		case 0x02:
			printf("VESA video display device data block\n");
			break;
		case 0x03:
			printf("VESA video timing block extension\n");
			break;
		case 0x04:
			printf("Reserved for HDMI video data block\n");
			break;
		case 0x05:
			printf("Colorimetry data block\n");
			cta_colorimetry_block(x + 2, length - 1);
			break;
		case 0x06:
			printf("HDR static metadata data block\n");
			cta_hdr_static_metadata_block(x + 2, length - 1);
			break;
		case 0x07:
			printf("HDR dynamic metadata data block\n");
			cta_hdr_dyn_metadata_block(x + 2, length - 1);
			break;
		case 0x0d:
			printf("Video format preference data block\n");
			cta_vfpdb(x + 2, length - 1);
			break;
		case 0x0e:
			printf("YCbCr 4:2:0 video data block\n");
			cta_y420vdb(x + 2, length - 1);
			break;
		case 0x0f:
			printf("YCbCr 4:2:0 capability map data block\n");
			cta_y420cmdb(x + 2, length - 1);
			break;
		case 0x10:
			printf("Reserved for CTA miscellaneous audio fields\n");
			break;
		case 0x11:
			printf("Vendor-specific audio data block\n");
			break;
		case 0x12:
			printf("HDMI audio data block\n");
			cta_hdmi_audio_block(x + 2, length - 1);
			break;
		case 0x13:
			printf("Room configuration data block\n");
			cta_rcdb(x + 2, length - 1);
			break;
		case 0x14:
			printf("Speaker location data block\n");
			cta_sldb(x + 2, length - 1);
			break;
		case 0x20:
			printf("InfoFrame data block\n");
			cta_ifdb(x + 2, length - 1);
			break;
		default:
			if (x[1] >= 6 && x[1] <= 12)
				printf("Reserved for video-related blocks (%02x)\n", x[1]);
			else if (x[1] >= 19 && x[1] <= 31)
				printf("Reserved for audio-related blocks (%02x)\n", x[1]);
			else
				printf("Reserved (%02x)\n", x[1]);
			break;
		}
		break;
	default: {
		int tag = (*x & 0xe0) >> 5;
		int length = *x & 0x1f;
		printf("  Unknown tag %d, length %d (raw %02x)\n", tag, length, *x);
		break;
	}
	}
	last_block_was_hdmi_vsdb = 0;
}

static int parse_cta(const unsigned char *x)
{
	int ret = 0;
	int version = x[1];
	int offset = x[2];
	const unsigned char *detailed;

	if (version >= 1) do {
		if (version == 1 && x[3] != 0)
			ret = 1;

		if (offset < 4)
			break;

		if (version < 3) {
			printf("%d 8-byte timing descriptors\n", (offset - 4) / 8);
			if (offset - 4 > 0)
				/* do stuff */ ;
		} else if (version == 3) {
			int i;
			printf("%d bytes of CTA data\n", offset - 4);
			for (i = 4; i < offset; i += (x[i] & 0x1f) + 1) {
				cta_block(x + i);
			}
		}

		if (version >= 2) {    
			if (x[3] & 0x80)
				printf("Underscans PC formats by default\n");
			if (x[3] & 0x40)
				printf("Basic audio support\n");
			if (x[3] & 0x20)
				printf("Supports YCbCr 4:4:4\n");
			if (x[3] & 0x10)
				printf("Supports YCbCr 4:2:2\n");
			printf("%d native detailed modes\n", x[3] & 0x0f);
		}

		for (detailed = x + offset; detailed + 18 < x + 127; detailed += 18)
			if (detailed[0])
				detailed_block(detailed, 1);
	} while (0);

	has_valid_cta_checksum = do_checksum(x, EDID_PAGE_SIZE);
	has_cta861 = 1;
	nonconformant_cta861_640x480 = !has_cta861_vic_1 && !has_640x480p60_est_timing;

	return ret;
}

static int parse_displayid_detailed_timing(const unsigned char *x)
{
	int ha, hbl, hso, hspw;
	int va, vbl, vso, vspw;
	char phsync, pvsync, *stereo;
	int pix_clock;
	char *aspect;

	switch (x[3] & 0xf) {
	case 0:
		aspect = "1:1";
		break;
	case 1:
		aspect = "5:4";
		break;
	case 2:
		aspect = "4:3";
		break;
	case 3:
		aspect = "15:9";
		break;
	case 4:
		aspect = "16:9";
		break;
	case 5:
		aspect = "16:10";
		break;
	case 6:
		aspect = "64:27";
		break;
	case 7:
		aspect = "256:135";
		break;
	default:
		aspect = "undefined";
		break;
	}
	switch ((x[3] >> 5) & 0x3) {
	case 0:
		stereo = "";
		break;
	case 1:
		stereo = "stereo";
		break;
	case 2:
		stereo = "user action";
		break;
	case 3:
		stereo = "reserved";
		break;
	}
	printf("Type 1 detailed timing: aspect: %s, %s %s\n", aspect, x[3] & 0x80 ? "Preferred " : "", stereo);
	pix_clock = x[0] + (x[1] << 8) + (x[2] << 16);
	ha = x[4] | (x[5] << 8);
	hbl = x[6] | (x[7] << 8);
	hso = x[8] | ((x[9] & 0x7f) << 8);
	phsync = ((x[9] >> 7) & 0x1) ? '+' : '-';
	hspw = x[10] | (x[11] << 8);
	va = x[12] | (x[13] << 8);
	vbl = x[14] | (x[15] << 8);
	vso = x[16] | ((x[17] & 0x7f) << 8);
	vspw = x[18] | (x[19] << 8);
	pvsync = ((x[17] >> 7) & 0x1 ) ? '+' : '-';

	printf("Detailed mode: Clock %.3f MHz, %d mm x %d mm\n"
	       "               %4d %4d %4d %4d\n"
	       "               %4d %4d %4d %4d\n"
	       "               %chsync %cvsync\n",
	       (float)pix_clock/100.0, 0, 0,
	       ha, ha + hso, ha + hso + hspw, ha + hbl,
	       va, va + vso, va + vso + vspw, va + vbl,
	       phsync, pvsync
	      );
	return 1;
}

static int parse_displayid(const unsigned char *x)
{
	int version = x[1];
	int length = x[2];
	int ext_count = x[4];
	int i;
	printf("Length %d, version %d, extension count %d\n", length, version, ext_count);

	/* DisplayID length field is number of following bytes
	 * but checksum is calculated over the entire structure
	 * (excluding DisplayID-in-EDID magic byte)
	 */
	has_valid_displayid_checksum = do_checksum(x+1, length + 5);

	int offset = 5;
	while (length > 0) {
		int tag = x[offset];
		int len = x[offset + 2];

		if (len == 0)
			break;
		switch (tag) {
		case 0:
			printf("Product ID block\n");
			break;
		case 1:
			printf("Display Parameters block\n");
			break;
		case 2:
			printf("Color characteristics block\n");
			break;
		case 3: {
			for (i = 0; i < len / 20; i++) {
				parse_displayid_detailed_timing(&x[offset + 3 + (i * 20)]);
			}
			break;
		}
		case 4:
			printf("Type 2 detailed timing\n");
			break;
		case 5:
			printf("Type 3 short timing\n");
			break;
		case 6:
			printf("Type 4 DMT timing\n");
			break;
		case 7:
			printf("VESA DMT timing block\n");
			break;
		case 8:
			printf("CTA timing block\n");
			break;
		case 9:
			printf("Video timing range\n");
			break;
		case 0xa:
			printf("Product serial number\n");
			break;
		case 0xb:
			printf("GP ASCII string\n");
			break;
		case 0xc:
			printf("Display device data\n");
			break;
		case 0xd:
			printf("Interface power sequencing\n");
			break;
		case 0xe:
			printf("Transfer characterisitics\n");
			break;
		case 0xf:
			printf("Display interface\n");
			break;
		case 0x10:
			printf("Stereo display interface\n");
			break;
		case 0x12: {
			int capabilities = x[offset + 3];
			int num_v_tile = (x[offset + 4] & 0xf) | (x[offset + 6] & 0x30);
			int num_h_tile = (x[offset + 4] >> 4) | ((x[offset + 6] >> 2) & 0x30);
			int tile_v_location = (x[offset + 5] & 0xf) | ((x[offset + 6] & 0x3) << 4);
			int tile_h_location = (x[offset + 5] >> 4) | (((x[offset + 6] >> 2) & 0x3) << 4);
			int tile_width = x[offset + 7] | (x[offset + 8] << 8);
			int tile_height = x[offset + 9] | (x[offset + 10] << 8);
			printf("tiled display block: capabilities 0x%08x\n", capabilities);
			printf("num horizontal tiles %d, num vertical tiles %d\n", num_h_tile + 1, num_v_tile + 1);
			printf("tile location (%d, %d)\n", tile_h_location, tile_v_location);
			printf("tile dimensions (%d, %d)\n", tile_width + 1, tile_height + 1);
			break;
		}
		default:
			printf("Unknown displayid data block 0x%x\n", tag);
			break;
		}
		length -= len + 3;
		offset += len + 3;
	}
	return 1;
}
/* generic extension code */

static void extension_version(const unsigned char *x)
{
	printf("Extension version: %d\n", x[1]);
}

static int parse_extension(const unsigned char *x)
{
	int conformant_extension;
	printf("\n");

	switch(x[0]) {
	case 0x02:
		printf("CTA extension block\n");
		extension_version(x);
		conformant_extension = parse_cta(x);
		break;
	case 0x10: printf("VTB extension block\n"); break;
	case 0x40: printf("DI extension block\n"); break;
	case 0x50: printf("LS extension block\n"); break;
	case 0x60: printf("DPVL extension block\n"); break;
	case 0x70: printf("DisplayID extension block\n");
		   extension_version(x);
		   parse_displayid(x);
		   break;
	case 0xF0: printf("Block map\n"); break;
	case 0xFF: printf("Manufacturer-specific extension block\n");
	default:
		   printf("Unknown extension block\n");
		   break;
	}

	printf("\n");

	return conformant_extension;
}

static int edid_lines = 0;

static unsigned char *extract_edid(int fd)
{
	char *ret = NULL;
	char *start, *c;
	unsigned char *out = NULL;
	int state = 0;
	int lines = 0;
	int i;
	int out_index = 0;
	int len, size;

	size = 1 << 10;
	ret = malloc(size);
	len = 0;

	if (ret == NULL)
		return NULL;

	for (;;) {
		i = read(fd, ret + len, size - len);
		if (i < 0) {
			free(ret);
			return NULL;
		}
		if (i == 0)
			break;
		len += i;
		if (len == size) {
			char *t;
			size <<= 1;
			t = realloc(ret, size);
			if (t == NULL) {
				free(ret);
				return NULL;
			}
			ret = t;
		}
	}

	start = strstr(ret, "EDID_DATA:");
	if (start == NULL)
		start = strstr(ret, "EDID:");
	/* Look for xrandr --verbose output (lines of 16 hex bytes) */
	if (start != NULL) {
		const char indentation1[] = "                ";
		const char indentation2[] = "\t\t";
		/* Used to detect that we've gone past the EDID property */
		const char half_indentation1[] = "        ";
		const char half_indentation2[] = "\t";
		const char *indentation;
		char *s;

		lines = 0;
		for (i = 0;; i++) {
			int j;

			/* Get the next start of the line of EDID hex, assuming spaces for indentation */
			s = strstr(start, indentation = indentation1);
			/* Did we skip the start of another property? */
			if (s && s > strstr(start, half_indentation1))
				break;

			/* If we failed, retry assuming tabs for indentation */
			if (!s) {
				s = strstr(start, indentation = indentation2);
				/* Did we skip the start of another property? */
				if (s && s > strstr(start, half_indentation2))
					break;
			}

			if (!s)
				break;

			lines++;
			start = s + strlen(indentation);

			s = realloc(out, lines * 16);
			if (!s) {
				free(ret);
				free(out);
				return NULL;
			}
			out = (unsigned char *)s;
			c = start;
			for (j = 0; j < 16; j++) {
				char buf[3];
				/* Read a %02x from the log */
				if (!isxdigit(c[0]) || !isxdigit(c[1])) {
					if (j != 0) {
						lines--;
						break;
					}
					free(ret);
					free(out);
					return NULL;
				}
				buf[0] = c[0];
				buf[1] = c[1];
				buf[2] = 0;
				out[out_index++] = strtol(buf, NULL, 16);
				c += 2;
			}
		}

		free(ret);
		edid_lines = lines;
		return out;
	}

	start = strstr(ret, "<BLOCK");
	if (start) {
		/* Parse QuantumData 980 EDID files */
		do {
			start = strstr(start, ">");
			if (start)
				out = realloc(out, out_index + 128);
			if (!start || !out) {
				free(ret);
				free(out);
				return NULL;
			}
			start++;
			for (i = 0; i < 256; i += 2) {
				char buf[3];

				buf[0] = start[i];
				buf[1] = start[i + 1];
				buf[2] = 0;
				out[out_index++] = strtol(buf, NULL, 16);
			}
			start = strstr(start, "<BLOCK");
		} while (start);
		edid_lines = out_index >> 4;
		return out;
	}

	/* Is the EDID provided in hex? */
	for (i = 0; i < 32 && (isspace(ret[i]) || ret[i] == ',' ||
			       tolower(ret[i]) == 'x' || isxdigit(ret[i])); i++);
	if (i == 32) {
		out = malloc(size >> 1);
		if (out == NULL) {
			free(ret);
			return NULL;
		}

		for (c=ret; *c; c++) {
			char buf[3];

			if (!isxdigit(*c) || (*c == '0' && tolower(c[1]) == 'x'))
				continue;

			/* Read a %02x from the log */
			if (!isxdigit(c[0]) || !isxdigit(c[1])) {
				free(ret);
				free(out);
				return NULL;
			}

			buf[0] = c[0];
			buf[1] = c[1];
			buf[2] = 0;

			out[out_index++] = strtol(buf, NULL, 16);
			c++;
		}

		free(ret);
		edid_lines = out_index >> 4;
		return out;
	}

	/* wait, is this a log file? */
	for (i = 0; i < 8; i++) {
		if (!isascii(ret[i])) {
			edid_lines = len / 16;
			return (unsigned char *)ret;
		}
	}

	/* I think it is, let's go scanning */
	if (!(start = strstr(ret, "EDID (in hex):")))
		return (unsigned char *)ret;
	if (!(start = strstr(start, "(II)")))
		return (unsigned char *)ret;

	for (c = start; *c; c++) {
		if (state == 0) {
			char *s;
			/* skip ahead to the : */
			s = strstr(c, ": \t");
			if (!s)
				s = strstr(c, ":     ");
			if (!s)
				break;
			c = s;
			/* and find the first number */
			while (!isxdigit(c[1]))
				c++;
			state = 1;
			lines++;
			s = realloc(out, lines * 16);
			if (!s) {
				free(ret);
				free(out);
				return NULL;
			}
			out = (unsigned char *)s;
		} else if (state == 1) {
			char buf[3];
			/* Read a %02x from the log */
			if (!isxdigit(*c)) {
				state = 0;
				continue;
			}
			buf[0] = c[0];
			buf[1] = c[1];
			buf[2] = 0;
			out[out_index++] = strtol(buf, NULL, 16);
			c++;
		}
	}

	edid_lines = lines;

	free(ret);

	return out;
}

static void print_subsection(char *name, const unsigned char *edid, int start,
			     int end)
{
	int i;

	printf("%s:", name);
	for (i = strlen(name); i < 15; i++)
		printf(" ");
	for (i = start; i <= end; i++)
		printf(" %02x", edid[i]);
	printf("\n");
}

static void dump_breakdown(const unsigned char *edid)
{
	printf("Extracted contents:\n");
	print_subsection("header", edid, 0, 7);
	print_subsection("serial number", edid, 8, 17);
	print_subsection("version", edid,18, 19);
	print_subsection("basic params", edid, 20, 24);
	print_subsection("chroma info", edid, 25, 34);
	print_subsection("established", edid, 35, 37);
	print_subsection("standard", edid, 38, 53);
	print_subsection("descriptor 1", edid, 54, 71);
	print_subsection("descriptor 2", edid, 72, 89);
	print_subsection("descriptor 3", edid, 90, 107);
	print_subsection("descriptor 4", edid, 108, 125);
	print_subsection("extensions", edid, 126, 126);
	print_subsection("checksum", edid, 127, 127);
	printf("\n");
}

static unsigned char crc_calc(const unsigned char *b)
{
	unsigned char sum = 0;
	int i;

	for (i = 0; i < 127; i++)
		sum += b[i];
	return 256 - sum;
}

static int crc_ok(const unsigned char *b)
{
	return crc_calc(b) == b[127];
}

static void hexdumpedid(FILE *f, const unsigned char *edid, unsigned size)
{
	unsigned b, i, j;

	for (b = 0; b < size / 128; b++) {
		const unsigned char *buf = edid + 128 * b;

		if (b)
			fprintf(f, "\n");
		for (i = 0; i < 128; i += 0x10) {
			fprintf(f, "%02x", buf[i]);
			for (j = 1; j < 0x10; j++) {
				fprintf(f, " %02x", buf[i + j]);
			}
			fprintf(f, "\n");
		}
		if (!crc_ok(buf))
			fprintf(f, "Block %u has a checksum error (should be 0x%02x)\n",
					b, crc_calc(buf));
	}
}

static void carraydumpedid(FILE *f, const unsigned char *edid, unsigned size)
{
	unsigned b, i, j;

	fprintf(f, "unsigned char edid[] = {\n");
	for (b = 0; b < size / 128; b++) {
		const unsigned char *buf = edid + 128 * b;

		if (b)
			fprintf(f, "\n");
		for (i = 0; i < 128; i += 8) {
			fprintf(f, "\t0x%02x,", buf[i]);
			for (j = 1; j < 8; j++) {
				fprintf(f, " 0x%02x,", buf[i + j]);
			}
			fprintf(f, "\n");
		}
		if (!crc_ok(buf))
			fprintf(f, "\t/* Block %u has a checksum error (should be 0x%02x) */\n",
					b, crc_calc(buf));
	}
	fprintf(f, "};\n");
}

static void write_edid(FILE *f, const unsigned char *edid, unsigned size,
		       enum output_format out_fmt)
{
	switch (out_fmt) {
	default:
	case OUT_FMT_HEX:
		hexdumpedid(f, edid, size);
		break;
	case OUT_FMT_RAW:
		fwrite(edid, size, 1, f);
		break;
	case OUT_FMT_CARRAY:
		carraydumpedid(f, edid, size);
		break;
	}
}

static int edid_from_file(const char *from_file, const char *to_file,
			  enum output_format out_fmt)
{
	int fd;
	FILE *out = NULL;
	unsigned char *edid;
	unsigned char *x;
	time_t the_time;
	struct tm *ptm;
	int analog, i;
	unsigned col_x, col_y;

	if (!from_file || !strcmp(from_file, "-")) {
		fd = 0;
	} else if ((fd = open(from_file, O_RDONLY)) == -1) {
		perror(from_file);
		return -1;
	}
	if (to_file) {
		if (!strcmp(to_file, "-")) {
			out = stdout;
		} else if ((out = fopen(to_file, "w")) == NULL) {
			perror(to_file);
			return -1;
		}
		if (out_fmt == OUT_FMT_DEFAULT)
			out_fmt = out == stdout ? OUT_FMT_HEX : OUT_FMT_RAW;
	}

	edid = extract_edid(fd);
	if (!edid) {
		fprintf(stderr, "edid extract failed\n");
		return -1;
	}
	if (fd != 0)
		close(fd);

	if (out) {
		write_edid(out, edid, edid_lines * 16, out_fmt);
		if (out == stdout)
			return 0;
		fclose(out);
	}

	if (options[OptExtract])
		dump_breakdown(edid);

	if (!edid || memcmp(edid, "\x00\xFF\xFF\xFF\xFF\xFF\xFF\x00", 8)) {
		fprintf(stderr, "No header found\n");
		return -1;
	}

	printf("EDID version: %hd.%hd\n", edid[0x12], edid[0x13]);
	if (edid[0x12] == 1) {
		if (edid[0x13] > 4) {
			printf("Claims > 1.4, assuming 1.4 conformance\n");
			edid[0x13] = 4;
		}
		edid_minor = edid[0x13];
		switch (edid[0x13]) {
		case 4:
			claims_one_point_four = 1;
		case 3:
			claims_one_point_three = 1;
		case 2:
			claims_one_point_two = 1;
		default:
			break;
		}
		claims_one_point_oh = 1;
	}

	printf("Manufacturer: %s Model %x Serial Number %u\n",
	       manufacturer_name(edid + 0x08),
	       (unsigned short)(edid[0x0A] + (edid[0x0B] << 8)),
	       (unsigned int)(edid[0x0C] + (edid[0x0D] << 8)
			      + (edid[0x0E] << 16) + (edid[0x0F] << 24)));
	has_valid_serial_number = edid[0x0C] || edid[0x0D] || edid[0x0E] || edid[0x0F];
	/* XXX need manufacturer ID table */

	time(&the_time);
	ptm = localtime(&the_time);
	if (edid[0x10] < 55 || (edid[0x10] == 0xff && claims_one_point_four)) {
		has_valid_week = 1;
		if (edid[0x11] > 0x0f) {
			if (edid[0x10] == 0xff) {
				has_valid_year = 1;
				printf("Model year %hd\n", edid[0x11] + 1990);
			} else if (edid[0x11] + 90 <= ptm->tm_year + 1) {
				has_valid_year = 1;
				if (edid[0x10])
					printf("Made in week %hd of %hd\n", edid[0x10], edid[0x11] + 1990);
				else
					printf("Made in year %hd\n", edid[0x11] + 1990);
			}
		}
	}

	/* display section */

	if (edid[0x14] & 0x80) {
		int conformance_mask;
		analog = 0;
		printf("Digital display\n");
		if (claims_one_point_four) {
			conformance_mask = 0;
			if ((edid[0x14] & 0x70) == 0x00)
				printf("Color depth is undefined\n");
			else if ((edid[0x14] & 0x70) == 0x70)
				nonconformant_digital_display = 1;
			else
				printf("%d bits per primary color channel\n",
				       ((edid[0x14] & 0x70) >> 3) + 4);

			switch (edid[0x14] & 0x0f) {
			case 0x00: printf("Digital interface is not defined\n"); break;
			case 0x01: printf("DVI interface\n"); break;
			case 0x02: printf("HDMI-a interface\n"); break;
			case 0x03: printf("HDMI-b interface\n"); break;
			case 0x04: printf("MDDI interface\n"); break;
			case 0x05: printf("DisplayPort interface\n"); break;
			default:
				   nonconformant_digital_display = 1;
			}
		} else if (claims_one_point_two) {
			conformance_mask = 0x7E;
			if (edid[0x14] & 0x01) {
				printf("DFP 1.x compatible TMDS\n");
			}
		} else conformance_mask = 0x7F;
		if (!nonconformant_digital_display)
			nonconformant_digital_display = edid[0x14] & conformance_mask;
	} else {
		analog = 1;
		int voltage = (edid[0x14] & 0x60) >> 5;
		int sync = (edid[0x14] & 0x0F);
		printf("Analog display, Input voltage level: %s V\n",
		       voltage == 3 ? "0.7/0.7" :
		       voltage == 2 ? "1.0/0.4" :
		       voltage == 1 ? "0.714/0.286" :
		       "0.7/0.3");

		if (claims_one_point_four) {
			if (edid[0x14] & 0x10)
				printf("Blank-to-black setup/pedestal\n");
			else
				printf("Blank level equals black level\n");
		} else if (edid[0x14] & 0x10) {
			/*
			 * XXX this is just the X text.  1.3 says "if set, display expects
			 * a blank-to-black setup or pedestal per appropriate Signal
			 * Level Standard".  Whatever _that_ means.
			 */
			printf("Configurable signal levels\n");
		}

		printf("Sync: %s%s%s%s\n", sync & 0x08 ? "Separate " : "",
		       sync & 0x04 ? "Composite " : "",
		       sync & 0x02 ? "SyncOnGreen " : "",
		       sync & 0x01 ? "Serration " : "");
	}

	if (edid[0x15] && edid[0x16])
		printf("Maximum image size: %d cm x %d cm\n", edid[0x15], edid[0x16]);
	else if (claims_one_point_four && (edid[0x15] || edid[0x16])) {
		if (edid[0x15])
			printf("Aspect ratio is %f (landscape)\n", 100.0/(edid[0x16] + 99));
		else
			printf("Aspect ratio is %f (portrait)\n", 100.0/(edid[0x15] + 99));
	} else {
		/* Either or both can be zero for 1.3 and before */
		printf("Image size is variable\n");
	}

	if (edid[0x17] == 0xff) {
		if (claims_one_point_four)
			printf("Gamma is defined in an extension block\n");
		else
			/* XXX Technically 1.3 doesn't say this... */
			printf("Gamma: 1.0\n");
	} else printf("Gamma: %.2f\n", ((edid[0x17] + 100.0) / 100.0));

	if (edid[0x18] & 0xE0) {
		printf("DPMS levels:");
		if (edid[0x18] & 0x80) printf(" Standby");
		if (edid[0x18] & 0x40) printf(" Suspend");
		if (edid[0x18] & 0x20) printf(" Off");
		printf("\n");
	}

	if (analog || !claims_one_point_four) {
		switch (edid[0x18] & 0x18) {
		case 0x00: printf("Monochrome or grayscale display\n"); break;
		case 0x08: printf("RGB color display\n"); break;
		case 0x10: printf("Non-RGB color display\n"); break;
		case 0x18: printf("Undefined display color type\n");
		}
	} else {
		printf("Supported color formats: RGB 4:4:4");
		if (edid[0x18] & 0x08)
			printf(", YCrCb 4:4:4");
		if (edid[0x18] & 0x10)
			printf(", YCrCb 4:2:2");
		printf("\n");
	}

	if (edid[0x18] & 0x04) {
		/*
		 * The sRGB chromaticities are (x, y):
		 * red:   0.640,  0.330
		 * green: 0.300,  0.600
		 * blue:  0.150,  0.060
		 * white: 0.3127, 0.3290
		 */
		static const unsigned char srgb_chromaticity[10] = {
			0xee, 0x91, 0xa3, 0x54, 0x4c, 0x99, 0x26, 0x0f, 0x50, 0x54
		};
		printf("Default (sRGB) color space is primary color space\n");
		nonconformant_srgb_chromaticity =
			memcmp(edid + 0x19, srgb_chromaticity, sizeof(srgb_chromaticity));
	}
	if (edid[0x18] & 0x02) {
		if (claims_one_point_four)
			printf("First detailed timing includes the native pixel format and preferred refresh rate\n");
		else
			printf("First detailed timing is preferred timing\n");
		has_preferred_timing = 1;
	} else if (claims_one_point_four) {
		/* 1.4 always has a preferred timing and this bit means something else. */
		has_preferred_timing = 1;
	}

	if (edid[0x18] & 0x01) {
		if (claims_one_point_four)
			printf("Display is continuous frequency\n");
		else
			printf("Supports GTF timings within operating range\n");
	}

	printf("Display x,y Chromaticity:\n");
	col_x = (edid[0x1b] << 2) | (edid[0x19] >> 6);
	col_y = (edid[0x1c] << 2) | ((edid[0x19] >> 4) & 3);
	printf("  Red:   0.%04u, 0.%04u\n",
	       (col_x * 10000) / 1024, (col_y * 10000) / 1024);
	col_x = (edid[0x1d] << 2) | ((edid[0x19] >> 2) & 3);
	col_y = (edid[0x1e] << 2) | (edid[0x19] & 3);
	printf("  Green: 0.%04u, 0.%04u\n",
	       (col_x * 10000) / 1024, (col_y * 10000) / 1024);
	col_x = (edid[0x1f] << 2) | (edid[0x1a] >> 6);
	col_y = (edid[0x20] << 2) | ((edid[0x1a] >> 4) & 3);
	printf("  Blue:  0.%04u, 0.%04u\n",
	       (col_x * 10000) / 1024, (col_y * 10000) / 1024);
	col_x = (edid[0x21] << 2) | ((edid[0x1a] >> 2) & 3);
	col_y = (edid[0x22] << 2) | (edid[0x1a] & 3);
	printf("  White: 0.%04u, 0.%04u\n",
	       (col_x * 10000) / 1024, (col_y * 10000) / 1024);

	printf("Established timings supported:\n");
	for (i = 0; i < 17; i++) {
		if (edid[0x23 + i / 8] & (1 << (7 - i % 8))) {
			min_vert_freq_hz = min(min_vert_freq_hz, established_timings[i].refresh);
			max_vert_freq_hz = max(max_vert_freq_hz, established_timings[i].refresh);
			min_hor_freq_hz = min(min_hor_freq_hz, established_timings[i].hor_freq_hz);
			max_hor_freq_hz = max(max_hor_freq_hz, established_timings[i].hor_freq_hz);
			max_pixclk_khz = max(max_pixclk_khz, established_timings[i].pixclk_khz);
			printf("  %dx%d%s@%dHz %u:%u HorFreq: %d Hz Clock: %.3f MHz\n",
			       established_timings[i].x, established_timings[i].y,
			       established_timings[i].interlaced ? "i" : "",
			       established_timings[i].refresh,
			       established_timings[i].ratio_w, established_timings[i].ratio_h,
			       established_timings[i].hor_freq_hz,
			       established_timings[i].pixclk_khz / 1000.0);
		}
	}
	has_640x480p60_est_timing = edid[0x23] & 0x20;

	printf("Standard timings supported:\n");
	for (i = 0; i < 8; i++)
		print_standard_timing(edid[0x26 + i * 2], edid[0x26 + i * 2 + 1]);

	/* detailed timings */
	has_valid_detailed_blocks = detailed_block(edid + 0x36, 0);
	if (has_preferred_timing && !did_detailed_timing)
		has_preferred_timing = 0; /* not really accurate... */
	has_valid_detailed_blocks &= detailed_block(edid + 0x48, 0);
	has_valid_detailed_blocks &= detailed_block(edid + 0x5A, 0);
	has_valid_detailed_blocks &= detailed_block(edid + 0x6C, 0);

	if (edid[0x7e])
		printf("Has %d extension blocks\n", edid[0x7e]);

	has_valid_checksum = do_checksum(edid, EDID_PAGE_SIZE);

	x = edid;
	for (edid_lines /= 8; edid_lines > 1; edid_lines--) {
		x += EDID_PAGE_SIZE;
		nonconformant_extension += parse_extension(x);
	}

	if (!options[OptCheck]) {
		free(edid);
		return 0;
	}

	if (claims_one_point_three) {
		if (nonconformant_digital_display ||
		    nonconformant_hf_vsdb_position ||
		    nonconformant_hdmi_vsdb_tmds_rate ||
		    nonconformant_hf_vsdb_tmds_rate ||
		    nonconformant_srgb_chromaticity ||
		    nonconformant_cta861_640x480 ||
		    !has_valid_string_termination ||
		    !has_valid_descriptor_pad ||
		    !has_name_descriptor ||
		    !has_preferred_timing ||
		    (!claims_one_point_four && !has_range_descriptor))
			conformant = 0;
		if (!conformant)
			printf("EDID block does NOT conform to EDID 1.%d!\n", edid_minor);
		if (nonconformant_srgb_chromaticity)
			printf("\tsRGB is signaled, but the chromaticities do not match\n");
		if (nonconformant_digital_display)
			printf("\tDigital display field contains garbage: %x\n",
			       nonconformant_digital_display);
		if (nonconformant_cta861_640x480)
			printf("\tRequired 640x480p60 timings are missing in the established timings\n"
			       "\tand/or in the SVD list (VIC 1)\n");
		if (nonconformant_hf_vsdb_position)
			printf("\tHDMI Forum VSDB did not immediately follow the HDMI VSDB\n");
		if (nonconformant_hdmi_vsdb_tmds_rate)
			printf("\tHDMI VSDB Max TMDS rate is > 340\n");
		if (nonconformant_hf_vsdb_tmds_rate)
			printf("\tHDMI Forum VSDB Max TMDS rate is > 0 and <= 340 or > 600\n");
		if (!has_name_descriptor)
			printf("\tMissing name descriptor\n");
		if (!has_preferred_timing)
			printf("\tMissing preferred timing\n");
		if (!has_range_descriptor)
			printf("\tMissing monitor ranges\n");
		if (!has_valid_descriptor_pad) /* Might be more than just 1.3 */
			printf("\tInvalid descriptor block padding\n");
		if (!has_valid_string_termination) /* Likewise */
			printf("\tDetailed block string not properly terminated\n");
	} else if (claims_one_point_two) {
		if (nonconformant_digital_display)
			conformant = 0;
		if (!conformant)
			printf("EDID block does NOT conform to EDID 1.2!\n");
		if (nonconformant_digital_display)
			printf("\tDigital display field contains garbage: %x\n",
			       nonconformant_digital_display);
	} else if (claims_one_point_oh) {
		if (seen_non_detailed_descriptor)
			conformant = 0;
		if (!conformant)
			printf("EDID block does NOT conform to EDID 1.0!\n");
		if (seen_non_detailed_descriptor)
			printf("\tHas descriptor blocks other than detailed timings\n");
	}

	if (has_range_descriptor && has_valid_range_descriptor &&
	    (min_vert_freq_hz < mon_min_vert_freq_hz ||
	     max_vert_freq_hz > mon_max_vert_freq_hz ||
	     min_hor_freq_hz < mon_min_hor_freq_hz ||
	     max_hor_freq_hz > mon_max_hor_freq_hz ||
	     max_pixclk_khz > mon_max_pixclk_khz)) {
		/*
		 * EDID 1.4 states (in an Errata) that explicitly defined
		 * timings supersede the monitor range definition.
		 */
		if (!claims_one_point_four)
			conformant = 0;
		else
			printf("Warning: ");
		printf("One or more of the timings is out of range of the Monitor Ranges:\n");
		printf("  Vertical Freq: %d - %d Hz\n", min_vert_freq_hz, max_vert_freq_hz);
		printf("  Horizontal Freq: %d - %d Hz\n", min_hor_freq_hz, max_hor_freq_hz);
		printf("  Maximum Clock: %.3f MHz\n", max_pixclk_khz / 1000.0);
	}

	if (nonconformant_extension ||
	    !has_valid_checksum ||
	    !has_valid_cvt ||
	    !has_valid_year ||
	    !has_valid_week ||
	    (has_cta861 && has_valid_serial_number && has_valid_serial_string) ||
	    !has_valid_detailed_blocks ||
	    !has_valid_dummy_block ||
	    !has_valid_descriptor_ordering ||
	    !has_valid_range_descriptor ||
	    !manufacturer_name_well_formed ||
	    (has_name_descriptor && !has_valid_name_descriptor) ||
	    (has_serial_string && !has_valid_serial_string) ||
	    (has_ascii_string && !has_valid_ascii_string) ||
	    empty_string ||
	    trailing_space) {
		conformant = 0;
		printf("EDID block does not conform at all!\n");
		if (nonconformant_extension)
			printf("\tHas %d nonconformant extension block(s)\n",
			       nonconformant_extension);
		if (!has_valid_checksum)
			printf("\tBlock has broken checksum\n");
		if (!has_valid_cvt)
			printf("\tBroken 3-byte CVT blocks\n");
		if (!has_valid_year)
			printf("\tBad year of manufacture\n");
		if (!has_valid_week)
			printf("\tBad week of manufacture\n");
		if (has_cta861 && has_valid_serial_number && has_valid_serial_string)
			printf("\tBoth the serial number and the serial string are set\n");
		if (!has_valid_detailed_blocks)
			printf("\tDetailed blocks filled with garbage\n");
		if (!has_valid_dummy_block)
			printf("\tDummy block filled with garbage\n");
		if (!manufacturer_name_well_formed)
			printf("\tManufacturer name field contains garbage\n");
		if (!has_valid_descriptor_ordering)
			printf("\tInvalid detailed timing descriptor ordering\n");
		if (!has_valid_range_descriptor)
			printf("\tRange descriptor contains garbage\n");
		if (!has_valid_max_dotclock)
			printf("\tEDID 1.4 block does not set max dotclock\n");
		if (has_name_descriptor && !has_valid_name_descriptor)
			printf("\tInvalid Monitor Name descriptor\n");
		if (has_ascii_string && !has_valid_ascii_string)
			printf("\tInvalid ASCII string\n");
		if (has_serial_string && !has_valid_serial_string)
			printf("\tInvalid serial string\n");
		if (trailing_space)
			printf("\tString contains one or more trailing spaces\n");
		if (empty_string)
			printf("\tString is empty\n");
	}

	if (!has_valid_cta_checksum) {
		printf("CTA extension block does not conform\n");
		printf("\tBlock has broken checksum\n");
	}
	if (!has_valid_displayid_checksum) {
		printf("DisplayID extension block does not conform\n");
		printf("\tBlock has broken checksum\n");
	}

	if (warning_excessive_dotclock_correction)
		printf("Warning: CVT block corrects dotclock by more than 9.75MHz\n");
	if (warning_zero_preferred_refresh)
		printf("Warning: CVT block does not set preferred refresh rate\n");
	if ((supported_hdmi_vic_vsb_codes & supported_hdmi_vic_codes) != supported_hdmi_vic_codes)
		printf("Warning: HDMI VIC Codes must have their CTA-861 VIC equivalents in the VSB\n");

	free(edid);
	return conformant ? 0 : -2;
}

int main(int argc, char **argv)
{
	char short_options[26 * 2 * 2 + 1];
	enum output_format out_fmt = OUT_FMT_DEFAULT;
	int ch;
	int i;

	while (1) {
		int option_index = 0;
		int idx = 0;

		for (i = 0; long_options[i].name; i++) {
			if (!isalpha(long_options[i].val))
				continue;
			short_options[idx++] = long_options[i].val;
			if (long_options[i].has_arg == required_argument)
				short_options[idx++] = ':';
		}
		short_options[idx] = 0;
		ch = getopt_long(argc, argv, short_options,
				 long_options, &option_index);
		if (ch == -1)
			break;

		options[(int)ch] = 1;
		switch (ch) {
		case OptHelp:
			usage();
			return -1;
		case OptOutputFormat:
			if (!strcmp(optarg, "hex")) {
				out_fmt = OUT_FMT_HEX;
			} else if (!strcmp(optarg, "raw")) {
				out_fmt = OUT_FMT_RAW;
			} else if (!strcmp(optarg, "carray")) {
				out_fmt = OUT_FMT_CARRAY;
			} else {
				usage();
				exit(1);
			}
			break;
		case ':':
			fprintf(stderr, "Option `%s' requires a value\n",
				argv[optind]);
			usage();
			return -1;
		case '?':
			fprintf(stderr, "Unknown argument `%s'\n",
				argv[optind]);
			usage();
			return -1;
		}
	}
	if (optind == argc)
		return edid_from_file(NULL, NULL, out_fmt);
	if (optind == argc - 1)
		return edid_from_file(argv[optind], NULL, out_fmt);
	return edid_from_file(argv[optind], argv[optind + 1], out_fmt);
}

/*
 * Notes on panel extensions: (TODO, implement me in the code)
 *
 * EPI: http://www.epi-standard.org/fileadmin/spec/EPI_Specification1.0.pdf
 * at offset 0x6c (fourth detailed block): (all other bits reserved)
 * 0x6c: 00 00 00 0e 00
 * 0x71: bit 6-5: data color mapping (00 conventional/fpdi/vesa, 01 openldi)
 *       bit 4-3: pixels per clock (00 1, 01 2, 10 4, 11 reserved)
 *       bit 2-0: bits per pixel (000 18, 001 24, 010 30, else reserved)
 * 0x72: bit 5: FPSCLK polarity (0 normal 1 inverted)
 *       bit 4: DE polarity (0 high active 1 low active)
 *       bit 3-0: interface (0000 LVDS TFT
 *                           0001 mono STN 4/8bit
 *                           0010 color STN 8/16 bit
 *                           0011 18 bit tft
 *                           0100 24 bit tft
 *                           0101 tmds
 *                           else reserved)
 * 0x73: bit 1: horizontal display mode (0 normal 1 right/left reverse)
 *       bit 0: vertical display mode (0 normal 1 up/down reverse)
 * 0x74: bit 7-4: total poweroff seq delay (0000 vga controller default
 *                                          else time in 10ms (10ms to 150ms))
 *       bit 3-0: total poweron seq delay (as above)
 * 0x75: contrast power on/off seq delay, same as 0x74
 * 0x76: bit 7: backlight control enable (1 means this field is valid)
 *       bit 6: backlight enabled at boot (0 on 1 off)
 *       bit 5-0: backlight brightness control steps (0..63)
 * 0x77: bit 7: contrast control, same bit pattern as 0x76 except bit 6 resvd
 * 0x78 - 0x7c: reserved
 * 0x7d: bit 7-4: EPI descriptor major version (1)
 *       bit 3-0: EPI descriptor minor version (0)
 *
 * ----
 *
 * SPWG: http://www.spwg.org/spwg_spec_version3.8_3-14-2007.pdf
 *
 * Since these are "dummy" blocks, terminate with 0a 20 20 20 ... as usual
 *
 * detailed descriptor 3:
 * 0x5a - 0x5e: 00 00 00 fe 00
 * 0x5f - 0x63: PC maker part number
 * 0x64: LCD supplier revision #
 * 0x65 - 0x6b: manufacturer part number
 *
 * detailed descriptor 4:
 * 0x6c - 0x70: 00 00 00 fe 00
 * 0x71 - 0x78: smbus nits values (whut)
 * 0x79: number of lvds channels (1 or 2)
 * 0x7A: panel self test (1 if present)
 * and then dummy terminator
 *
 * SPWG also says something strange about the LSB of detailed descriptor 1:
 * "LSB is set to "1" if panel is DE-timing only. H/V can be ignored."
 */