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 3438 3439 3440 3441 3442 3443 3444 3445 3446 3447 3448 3449 3450 3451 3452 3453 3454 3455 3456 3457 3458 3459 3460 3461 3462 3463 3464 3465 3466 3467 3468 3469 3470 3471 3472 3473 3474 3475 3476 3477 3478 3479 3480 3481 3482 3483 3484 3485 3486 3487 3488 3489 3490 3491 3492 3493 3494 3495 3496 3497 3498 3499 3500 3501 3502 3503 3504 3505 3506 3507 3508 3509 3510 3511 3512 3513 3514 3515 3516 3517 3518 3519 3520 3521 3522 3523 3524 3525 3526 3527 3528 3529 3530 3531 3532 3533 3534 3535 3536 3537 3538 3539 3540 3541 3542 3543 3544 3545 3546 3547 3548 3549 3550 3551 3552 3553 3554 3555 3556 3557 3558 3559 3560 3561 3562 3563 3564 3565 3566 3567 3568 3569 3570 3571 3572 3573 3574 3575 3576 3577 3578 3579 3580 3581 3582 3583 3584 3585 3586 3587 3588 3589 3590 3591 3592 3593 3594 3595 3596 3597 3598 3599 3600 3601 3602 3603 3604 3605 3606 3607 3608 3609 3610 3611 3612 3613 3614 3615 3616 3617 3618 3619 3620 3621 3622 3623 3624 3625 3626 3627 3628 3629 3630 3631 3632 3633 3634 3635 3636 3637 3638 3639 3640 3641 3642 3643 3644 3645 3646 3647 3648 3649 3650 3651 3652 3653 3654 3655 3656 3657 3658 3659 3660 3661 3662 3663 3664 3665 3666 3667 3668 3669 3670 3671 3672 3673 3674 3675 3676 3677 3678 3679 3680 3681 3682 3683 3684 3685 3686 3687 3688 3689 3690 3691 3692 3693 3694 3695 3696 3697 3698 3699 3700 3701 3702 3703 3704 3705 3706 3707 3708 3709 3710 3711 3712 3713 3714 3715 3716 3717 3718 3719 3720 3721 3722 3723 3724 3725 3726 3727 3728 3729 3730 3731 3732 3733 3734 3735 3736 3737 3738 3739 3740 3741 3742 3743 3744 3745 3746 3747 3748 3749 3750 3751 3752 3753 3754 3755 3756 3757 3758 3759 3760 3761 3762 3763 3764 3765 3766 3767 3768 3769 3770 3771 3772 3773 3774 3775 3776 3777 3778 3779 3780 3781 3782 3783 3784 3785 3786 3787 3788 3789 3790 3791 3792 3793 3794 3795 3796 3797 3798 3799 3800 3801 3802 3803 3804 3805 3806 3807 3808 3809 3810 3811 3812 3813 3814 3815 3816 3817 3818 3819 3820 3821 3822 3823 3824 3825 3826 3827 3828 3829 3830 3831 3832 3833 3834 3835 3836 3837 3838 3839 3840 3841 3842 3843 3844 3845 3846 3847 3848 3849 3850 3851 3852 3853 3854 3855 3856 3857 3858 3859 3860 3861 3862 3863 3864 3865 3866 3867 3868 3869 3870 3871 3872 3873 3874 3875 3876 3877 3878 3879 3880 3881 3882 3883 3884 3885 3886 3887 3888 3889 3890 3891 3892 3893 3894 3895 3896 3897 3898 3899 3900 3901 3902 3903 3904 3905 3906 3907 3908 3909 3910 3911 3912 3913 3914 3915 3916 3917 3918 3919 3920 3921 3922 3923 3924 3925 3926 3927 3928 3929 3930 3931 3932 3933 3934 3935 3936 3937 3938 3939 3940 3941 3942 3943 3944 3945 3946 3947 3948 3949 3950 3951 3952 3953 3954 3955 3956 3957 3958 3959 3960 3961 3962 3963 3964 3965 3966 3967 3968 3969 3970 3971 3972 3973 3974 3975 3976 3977 3978 3979 3980 3981 3982 3983 3984 3985 3986 3987 3988 3989 3990 3991 3992 3993 3994 3995 3996 3997 3998 3999 4000 4001 4002 4003 4004 4005 4006 4007 4008 4009 4010 4011 4012 4013 4014 4015 4016 4017 4018 4019 4020 4021 4022 4023 4024 4025 4026 4027 4028 4029 4030 4031 4032 4033 4034 4035 4036 4037 4038 4039 4040 4041 4042 4043 4044 4045 4046 4047 4048 4049 4050 4051 4052 4053 4054 4055 4056 4057 4058 4059 4060 4061 4062 4063 4064 4065 4066 4067 4068 4069 4070 4071 4072 4073 4074 4075 4076 4077 4078 4079 4080 4081 4082 4083 4084 4085 4086 4087 4088 4089 4090 4091 4092 4093 4094 4095 4096 4097 4098 4099 4100 4101 4102 4103 4104 4105 4106 4107 4108 4109 4110 4111 4112 4113 4114 4115 4116 4117 4118 4119 4120 4121 4122 4123 4124 4125 4126 4127 4128 4129 4130 4131 4132 4133 4134 4135 4136 4137 4138 4139 4140 4141 4142 4143 4144 4145 4146 4147 4148 4149 4150 4151 4152 4153 4154 4155 4156 4157 4158 4159 4160 4161 4162 4163 4164 4165 4166 4167 4168 4169 4170 4171 4172 4173 4174 4175 4176 4177 4178 4179 4180 4181 4182 4183 4184 4185 4186 4187 4188 4189 4190 4191 4192 4193 4194 4195 4196 4197 4198 4199 4200 4201 4202 4203 4204 4205 4206 4207 4208 4209 4210 4211 4212 4213 4214 4215 4216 4217 4218 4219 4220 4221 4222 4223 4224 4225 4226 4227 4228 4229 4230 4231 4232 4233 4234 4235 4236 4237 4238 4239 4240 4241 4242 4243 4244 4245 4246 4247 4248 4249 4250 4251 4252 4253 4254 4255 4256 4257 4258 4259 4260 4261 4262 4263 4264 4265 4266 4267 4268 4269 4270 4271 4272 4273 4274 4275 4276 4277 4278 4279 4280 4281 4282 4283 4284 4285 4286 4287 4288 4289 4290 4291 4292 4293 4294 4295 4296 4297 4298 4299 4300 4301 4302 4303 4304 4305 4306 4307 4308 4309 4310 4311 4312 4313 4314 4315 4316 4317 4318 4319 4320 4321 4322 4323 4324 4325 4326 4327 4328 4329 4330 4331 4332 4333 4334 4335 4336 4337 4338 4339 4340 4341 4342 4343 4344 4345 4346 4347 4348 4349 4350 4351 4352 4353 4354 4355 4356 4357 4358 4359 4360 4361 4362 4363 4364 4365 4366 4367 4368 4369 4370 4371 4372 4373 4374 4375 4376 4377 4378 4379 4380 4381 4382 4383 4384 4385 4386 4387 4388 4389 4390 4391 4392 4393 4394 4395 4396 4397 4398 4399 4400 4401 4402 4403 4404 4405 4406 4407 4408 4409 4410 4411 4412 4413 4414 4415 4416 4417 4418 4419 4420 4421 4422 4423 4424 4425 4426 4427 4428 4429 4430 4431 4432 4433 4434 4435 4436 4437 4438 4439 4440 4441 4442 4443 4444 4445 4446 4447 4448 4449 4450 4451 4452 4453 4454 4455 4456 4457 4458 4459 4460 4461 4462 4463 4464 4465 4466 4467 4468 4469 4470 4471 4472 4473 4474 4475 4476 4477 4478 4479 4480 4481 4482 4483 4484 4485 4486 4487 4488 4489 4490 4491 4492 4493 4494 4495 4496 4497 4498 4499 4500 4501 4502 4503 4504 4505 4506 4507 4508 4509 4510 4511 4512 4513 4514 4515 4516 4517 4518 4519 4520 4521 4522 4523 4524 4525 4526 4527 4528 4529 4530 4531 4532 4533 4534 4535 4536 4537 4538 4539 4540 4541 4542 4543 4544 4545 4546 4547 4548 4549 4550 4551 4552 4553 4554 4555 4556 4557 4558 4559 4560 4561 4562 4563 4564 4565 4566 4567 4568 4569 4570 4571 4572 4573 4574 4575 4576 4577 4578 4579 4580 4581 4582 4583 4584 4585 4586 4587 4588 4589 4590 4591 4592 4593 4594 4595 4596 4597 4598 4599 4600 4601 4602 4603 4604 4605 4606 4607 4608 4609 4610 4611 4612 4613 4614 4615 4616 4617 4618 4619 4620 4621 4622 4623 4624 4625 4626 4627 4628 4629 4630 4631 4632 4633 4634 4635 4636 4637 4638 4639 4640 4641 4642 4643 4644 4645 4646 4647 4648 4649 4650 4651 4652 4653 4654 4655 4656 4657 4658 4659 4660 4661 4662 4663 4664 4665 4666 4667 4668 4669 4670 4671 4672 4673 4674 4675 4676 4677 4678 4679 4680 4681 4682 4683 4684 4685 4686 4687 4688 4689 4690 4691 4692 4693 4694 4695 4696 4697 4698 4699 4700 4701 4702 4703 4704 4705 4706 4707 4708 4709 4710 4711 4712 4713 4714 4715 4716 4717 4718 4719 4720 4721 4722 4723 4724 4725 4726 4727 4728 4729 4730 4731 4732 4733 4734 4735 4736 4737 4738 4739 4740 4741 4742 4743 4744 4745 4746 4747 4748 4749 4750 4751 4752 4753 4754 4755 4756 4757 4758 4759 4760 4761 4762 4763 4764 4765 4766 4767 4768 4769 4770 4771 4772 4773 4774 4775 4776 4777 4778 4779 4780 4781 4782 4783 4784 4785 4786 4787 4788 4789 4790 4791 4792 4793 4794 4795 4796 4797 4798 4799 4800 4801 4802 4803 4804 4805 4806 4807 4808 4809 4810 4811 4812 4813 4814 4815 4816 4817 4818 4819 4820 4821 4822 4823 4824 4825 4826 4827 4828 4829 4830 4831 4832 4833 4834 4835 4836 4837 4838 4839 4840 4841 4842 4843 4844 4845 4846 4847 4848 4849 4850 4851 4852 4853 4854 4855 4856 4857 4858 4859 4860 4861 4862 4863 4864 4865 4866 4867 4868 4869 4870 4871 4872 4873 4874 4875 4876 4877 4878 4879 4880 4881 4882 4883 4884 4885 4886 4887 4888 4889 4890 4891 4892 4893 4894 4895 4896 4897 4898 4899 4900 4901 4902 4903 4904 4905 4906 4907 4908 4909 4910 4911 4912 4913 4914 4915 4916 4917 4918 4919 4920 4921 4922 4923 4924 4925 4926 4927 4928 4929 4930 4931 4932 4933 4934 4935 4936 4937 4938 4939 4940 4941 4942 4943 4944 4945 4946 4947 4948 4949 4950 4951 4952 4953 4954 4955 4956 4957 4958 4959 4960 4961 4962 4963 4964 4965 4966 4967 4968 4969 4970 4971 4972 4973 4974 4975 4976 4977 4978 4979 4980 4981 4982 4983 4984 4985 4986 4987 4988 4989 4990 4991 4992 4993 4994 4995 4996 4997 4998 4999 5000 5001 5002 5003 5004 5005 5006 5007 5008 5009 5010 5011 5012 5013 5014 5015 5016 5017 5018 5019 5020 5021 5022 5023 5024 5025 5026 5027 5028 5029 5030 5031 5032 5033 5034 5035 5036 5037 5038 5039 5040 5041 5042 5043 5044 5045 5046 5047 5048 5049 5050 5051 5052 5053 5054 5055 5056 5057 5058 5059 5060 5061 5062 5063 5064 5065 5066 5067 5068 5069 5070 5071 5072 5073 5074 5075 5076 5077 5078 5079 5080 5081 5082 5083 5084 5085 5086 5087 5088 5089 5090 5091 5092 5093 5094 5095 5096 5097 5098 5099 5100 5101 5102 5103 5104 5105 5106 5107 5108 5109 5110 5111 5112 5113 5114 5115 5116 5117 5118 5119 5120 5121 5122 5123 5124 5125 5126 5127 5128 5129 5130 5131 5132 5133 5134 5135 5136 5137 5138 5139 5140 5141 5142 5143 5144 5145 5146 5147 5148 5149 5150 5151 5152 5153 5154 5155 5156 5157 5158 5159 5160 5161 5162 5163 5164 5165 5166 5167 5168 5169 5170 5171 5172 5173 5174 5175 5176 5177 5178 5179 5180 5181 5182 5183 5184 5185 5186 5187 5188 5189 5190 5191 5192 5193 5194 5195 5196 5197 5198 5199 5200 5201 5202 5203 5204 5205 5206 5207 5208 5209 5210 5211 5212 5213 5214 5215 5216 5217 5218 5219 5220 5221 5222 5223 5224 5225 5226 5227 5228 5229 5230 5231 5232 5233 5234 5235 5236 5237 5238 5239 5240 5241 5242 5243 5244 5245 5246 5247 5248 5249 5250 5251 5252 5253 5254 5255 5256 5257 5258 5259 5260 5261 5262 5263 5264 5265 5266 5267 5268 5269 5270 5271 5272 5273 5274 5275 5276 5277 5278 5279 5280 5281 5282 5283 5284 5285 5286 5287 5288 5289 5290 5291 5292 5293 5294 5295 5296 5297 5298 5299 5300 5301 5302 5303 5304 5305 5306 5307 5308 5309 5310 5311 5312 5313 5314 5315 5316 5317 5318 5319 5320 5321 5322 5323 5324 5325 5326 5327 5328 5329 5330 5331 5332 5333 5334 5335 5336 5337 5338 5339 5340 5341 5342 5343 5344 5345 5346 5347 5348 5349 5350 5351 5352 5353 5354 5355 5356 5357 5358 5359 5360 5361 5362 5363 5364 5365 5366 5367 5368 5369 5370 5371 5372 5373 5374 5375 5376 5377 5378 5379 5380 5381 5382 5383 5384 5385 5386 5387 5388 5389 5390 5391 5392 5393 5394 5395 5396 5397 5398 5399 5400 5401 5402 5403 5404 5405 5406 5407 5408 5409 5410 5411 5412 5413 5414 5415 5416 5417 5418 5419 5420 5421 5422 5423 5424 5425 5426 5427 5428 5429 5430 5431 5432 5433 5434 5435 5436 5437 5438 5439 5440 5441 5442 5443 5444 5445 5446 5447 5448 5449 5450 5451 5452 5453 5454 5455 5456 5457 5458 5459 5460 5461 5462 5463 5464 5465 5466 5467 5468 5469 5470 5471 5472 5473 5474 5475 5476 5477 5478 5479 5480 5481 5482 5483 5484 5485 5486 5487 5488 5489 5490 5491 5492 5493 5494 5495 5496 5497 5498 5499 5500 5501 5502 5503 5504 5505 5506 5507 5508 5509 5510 5511 5512 5513 5514 5515 5516 5517 5518 5519 5520 5521 5522 5523 5524 5525 5526 5527 5528 5529 5530 5531 5532 5533 5534 5535 5536 5537 5538 5539 5540 5541 5542 5543 5544 5545 5546 5547 5548 5549 5550 5551 5552 5553 5554 5555 5556 5557 5558 5559 5560 5561 5562 5563 5564 5565 5566 5567 5568 5569 5570 5571 5572 5573 5574 5575 5576 5577 5578 5579 5580 5581 5582 5583 5584 5585 5586 5587 5588 5589 5590 5591 5592 5593 5594 5595 5596 5597 5598 5599 5600 5601 5602 5603 5604 5605 5606 5607 5608 5609 5610 5611 5612 5613 5614 5615 5616 5617 5618 5619 5620 5621 5622 5623 5624 5625 5626 5627 5628 5629 5630 5631 5632 5633 5634 5635 5636 5637 5638 5639 5640 5641 5642 5643 5644 5645 5646 5647 5648 5649 5650 5651 5652 5653 5654 5655 5656 5657 5658 5659 5660 5661 5662 5663 5664 5665 5666 5667 5668 5669 5670 5671 5672 5673 5674 5675 5676 5677 5678 5679 5680 5681 5682 5683 5684 5685 5686 5687 5688 5689 5690 5691 5692 5693 5694 5695 5696 5697 5698 5699 5700 5701 5702 5703 5704 5705 5706 5707 5708 5709 5710 5711 5712 5713 5714 5715 5716 5717 5718 5719 5720 5721 5722 5723 5724 5725 5726 5727 5728 5729 5730 5731 5732 5733 5734 5735 5736 5737 5738 5739 5740 5741 5742 5743 5744 5745 5746 5747 5748 5749 5750 5751 5752 5753 5754 5755 5756 5757 5758 5759 5760 5761 5762 5763 5764 5765 5766 5767 5768 5769 5770 5771 5772 5773 5774 5775 5776 5777 5778 5779 5780 5781 5782 5783 5784 5785 5786 5787 5788 5789 5790 5791 5792 5793 5794 5795 5796 5797 5798 5799 5800 5801 5802 5803 5804 5805 5806 5807 5808 5809 5810 5811 5812 5813 5814 5815 5816 5817 5818 5819 5820 5821 5822 5823 5824 5825 5826 5827 5828 5829 5830 5831 5832 5833 5834 5835 5836 5837 5838 5839 5840 5841 5842 5843 5844 5845 5846 5847 5848 5849 5850 5851 5852 5853 5854 5855 5856 5857 5858 5859 5860 5861 5862 5863 5864 5865 5866 5867 5868 5869 5870 5871 5872 5873 5874 5875 5876 5877 5878 5879 5880 5881 5882 5883 5884 5885 5886 5887 5888 5889 5890 5891 5892 5893 5894 5895 5896 5897 5898 5899 5900 5901 5902 5903 5904 5905 5906 5907 5908 5909 5910 5911 5912 5913 5914 5915 5916 5917 5918 5919 5920 5921 5922 5923 5924 5925 5926 5927 5928 5929 5930 5931 5932 5933 5934 5935 5936 5937 5938 5939 5940 5941 5942 5943 5944 5945 5946 5947 5948 5949 5950 5951 5952 5953 5954 5955 5956 5957 5958 5959 5960 5961 5962 5963 5964 5965 5966 5967 5968 5969 5970 5971 5972 5973 5974 5975 5976 5977 5978 5979 5980 5981 5982 5983 5984 5985 5986 5987 5988 5989 5990 5991 5992 5993 5994 5995 5996 5997 5998 5999 6000 6001 6002 6003 6004 6005 6006 6007 6008 6009 6010 6011 6012 6013 6014 6015 6016 6017 6018 6019 6020 6021 6022 6023 6024 6025 6026 6027 6028 6029 6030 6031 6032 6033 6034 6035 6036 6037 6038 6039 6040 6041 6042 6043 6044 6045 6046 6047 6048 6049 6050 6051 6052 6053 6054 6055 6056 6057 6058 6059 6060 6061 6062 6063 6064 6065 6066 6067 6068 6069 6070 6071 6072 6073 6074 6075 6076 6077 6078 6079 6080 6081 6082 6083 6084 6085 6086 6087 6088 6089 6090 6091 6092 6093 6094 6095 6096 6097 6098 6099 6100 6101 6102 6103 6104 6105 6106 6107 6108 6109 6110 6111 6112 6113 6114 6115 6116 6117 6118 6119 6120 6121 6122 6123 6124 6125 6126 6127 6128 6129 6130 6131 6132 6133 6134 6135 6136 6137 6138 6139 6140 6141 6142 6143 6144 6145 6146 6147 6148 6149 6150 6151 6152 6153 6154 6155 6156 6157 6158 6159 6160 6161 6162 6163 6164 6165 6166 6167 6168 6169 6170 6171 6172 6173 6174 6175 6176 6177 6178 6179 6180 6181 6182 6183 6184 6185 6186 6187 6188 6189 6190 6191 6192 6193 6194 6195 6196 6197 6198 6199 6200 6201 6202 6203 6204 6205 6206 6207 6208 6209 6210 6211 6212 6213 6214 6215 6216 6217 6218 6219 6220 6221 6222 6223 6224 6225 6226 6227 6228 6229 6230 6231 6232 6233 6234 6235 6236 6237 6238 6239 6240 6241 6242 6243 6244 6245 6246 6247 6248 6249 6250 6251 6252 6253 6254 6255 6256 6257 6258 6259 6260 6261 6262 6263 6264 6265 6266 6267 6268 6269 6270 6271 6272 6273 6274 6275 6276 6277 6278 6279 6280 6281 6282 6283 6284 6285 6286 6287 6288 6289 6290 6291 6292 6293 6294 6295 6296 6297 6298 6299 6300 6301 6302 6303 6304 6305 6306 6307 6308 6309 6310 6311 6312 6313 6314 6315 6316 6317 6318 6319 6320 6321 6322 6323 6324 6325 6326 6327 6328 6329 6330 6331 6332 6333 6334 6335 6336 6337 6338 6339 6340 6341 6342 6343 6344 6345 6346 6347 6348 6349 6350 6351 6352 6353 6354 6355 6356 6357 6358 6359 6360 6361 6362 6363 6364 6365 6366 6367 6368 6369 6370 6371 6372 6373 6374 6375 6376 6377 6378 6379 6380 6381 6382 6383 6384 6385 6386 6387 6388 6389 6390 6391 6392 6393 6394 6395 6396 6397 6398 6399 6400 6401 6402 6403 6404 6405 6406 6407 6408 6409 6410 6411 6412 6413 6414 6415 6416 6417 6418 6419 6420 6421 6422 6423 6424 6425 6426 6427 6428 6429 6430 6431 6432 6433 6434 6435 6436 6437 6438 6439 6440 6441 6442 6443 6444 6445 6446 6447 6448 6449 6450 6451 6452 6453 6454 6455 6456 6457 6458 6459 6460 6461 6462 6463 6464 6465 6466 6467 6468 6469 6470 6471 6472 6473 6474 6475 6476 6477 6478 6479 6480 6481 6482 6483 6484 6485 6486 6487 6488 6489 6490 6491 6492 6493 6494 6495 6496 6497 6498 6499 6500 6501 6502 6503 6504 6505 6506 6507 6508 6509 6510 6511 6512 6513 6514 6515 6516 6517 6518 6519 6520 6521 6522 6523 6524 6525 6526 6527 6528 6529 6530 6531 6532 6533 6534 6535 6536 6537 6538 6539 6540 6541 6542 6543 6544 6545 6546 6547 6548 6549 6550 6551 6552 6553 6554 6555 6556 6557 6558 6559 6560 6561 6562 6563 6564 6565 6566 6567 6568 6569 6570 6571 6572 6573 6574 6575 6576 6577 6578 6579 6580 6581 6582 6583 6584 6585 6586 6587 6588 6589 6590 6591 6592 6593 6594 6595 6596 6597 6598 6599 6600 6601 6602 6603 6604 6605 6606 6607 6608 6609 6610 6611 6612 6613 6614 6615 6616 6617 6618 6619 6620 6621 6622 6623 6624 6625 6626 6627 6628 6629 6630 6631 6632 6633 6634 6635 6636 6637 6638 6639 6640 6641 6642 6643 6644 6645 6646 6647 6648 6649 6650 6651 6652 6653 6654 6655 6656 6657 6658 6659 6660 6661 6662 6663 6664 6665 6666 6667 6668 6669 6670 6671 6672 6673 6674 6675 6676 6677 6678 6679 6680 6681 6682 6683 6684 6685 6686 6687 6688 6689 6690 6691 6692 6693 6694 6695 6696 6697 6698 6699 6700 6701 6702 6703 6704 6705 6706 6707 6708 6709 6710 6711 6712 6713 6714 6715 6716 6717 6718 6719 6720 6721 6722 6723 6724 6725 6726 6727 6728 6729 6730 6731 6732 6733 6734 6735 6736 6737 6738 6739 6740 6741 6742 6743 6744 6745 6746 6747 6748 6749 6750 6751 6752 6753 6754 6755 6756 6757 6758 6759 6760 6761 6762 6763 6764 6765 6766 6767 6768 6769 6770 6771 6772 6773 6774 6775 6776 6777 6778 6779 6780 6781 6782 6783 6784 6785 6786 6787 6788 6789 6790 6791 6792 6793 6794 6795 6796 6797 6798 6799 6800 6801 6802 6803 6804 6805 6806 6807 6808 6809 6810 6811 6812 6813 6814 6815 6816 6817 6818 6819 6820 6821 6822 6823 6824 6825 6826 6827 6828 6829 6830 6831 6832 6833 6834 6835 6836 6837 6838 6839 6840 6841 6842 6843 6844 6845 6846 6847 6848 6849 6850 6851 6852 6853 6854 6855 6856 6857 6858 6859 6860 6861 6862 6863 6864 6865 6866 6867 6868 6869 6870 6871 6872 6873 6874 6875 6876 6877 6878 6879 6880 6881 6882 6883 6884 6885 6886 6887 6888 6889 6890 6891 6892 6893 6894 6895 6896 6897 6898 6899 6900 6901 6902 6903 6904 6905 6906 6907 6908 6909 6910 6911 6912 6913 6914 6915 6916 6917 6918 6919 6920 6921 6922 6923 6924 6925 6926 6927 6928 6929 6930 6931 6932 6933 6934 6935 6936 6937 6938 6939 6940 6941 6942 6943 6944 6945 6946 6947 6948 6949 6950 6951 6952 6953 6954 6955 6956 6957 6958 6959 6960 6961 6962 6963 6964 6965 6966 6967 6968 6969 6970 6971 6972 6973 6974 6975 6976 6977 6978 6979 6980 6981 6982 6983 6984 6985 6986 6987 6988 6989 6990 6991 6992 6993 6994 6995 6996 6997 6998 6999 7000 7001 7002 7003 7004 7005 7006 7007 7008 7009 7010 7011 7012 7013 7014 7015 7016 7017 7018 7019 7020 7021 7022 7023 7024 7025 7026 7027 7028 7029 7030 7031 7032 7033 7034 7035 7036 7037 7038 7039 7040 7041 7042 7043 7044 7045 7046 7047 7048 7049 7050 7051 7052 7053 7054 7055 7056 7057 7058 7059 7060 7061 7062 7063 7064 7065 7066 7067 7068 7069 7070 7071 7072 7073 7074 7075 7076 7077 7078 7079 7080 7081 7082 7083 7084 7085 7086 7087 7088 7089 7090 7091 7092 7093 7094 7095 7096 7097 7098 7099 7100 7101 7102 7103 7104 7105 7106 7107 7108 7109 7110 7111 7112 7113 7114 7115 7116 7117 7118 7119 7120 7121 7122 7123 7124 7125 7126 7127 7128 7129 7130 7131 7132 7133 7134 7135 7136 7137 7138 7139 7140 7141 7142 7143 7144 7145 7146 7147 7148 7149 7150 7151 7152 7153 7154 7155 7156 7157 7158 7159 7160 7161 7162 7163 7164 7165 7166 7167 7168 7169 7170 7171 7172 7173 7174 7175 7176 7177 7178 7179 7180 7181 7182 7183 7184 7185 7186 7187 7188 7189 7190 7191 7192 7193 7194 7195 7196 7197 7198 7199 7200 7201 7202 7203 7204 7205 7206 7207 7208 7209 7210 7211 7212 7213 7214 7215 7216 7217 7218 7219 7220 7221 7222 7223 7224 7225 7226 7227 7228 7229 7230 7231 7232 7233 7234 7235 7236 7237 7238 7239 7240 7241 7242 7243 7244 7245 7246 7247 7248 7249 7250 7251 7252 7253 7254 7255 7256 7257 7258 7259 7260 7261
|
// Copyright 2019 Joe Drago. All rights reserved.
// SPDX-License-Identifier: BSD-2-Clause
#include "avif/avif.h"
#include "avif/internal.h"
#include <assert.h>
#include <ctype.h>
#include <inttypes.h>
#include <limits.h>
#include <math.h>
#include <stdio.h>
#include <string.h>
#define AUXTYPE_SIZE 64
#define CONTENTTYPE_SIZE 64
// class VisualSampleEntry(codingname) extends SampleEntry(codingname) {
// unsigned int(16) pre_defined = 0;
// const unsigned int(16) reserved = 0;
// unsigned int(32)[3] pre_defined = 0;
// unsigned int(16) width;
// unsigned int(16) height;
// template unsigned int(32) horizresolution = 0x00480000; // 72 dpi
// template unsigned int(32) vertresolution = 0x00480000; // 72 dpi
// const unsigned int(32) reserved = 0;
// template unsigned int(16) frame_count = 1;
// string[32] compressorname;
// template unsigned int(16) depth = 0x0018;
// int(16) pre_defined = -1;
// // other boxes from derived specifications
// CleanApertureBox clap; // optional
// PixelAspectRatioBox pasp; // optional
// }
static const size_t VISUALSAMPLEENTRY_SIZE = 78;
// The only supported ipma box values for both version and flags are [0,1], so there technically
// can't be more than 4 unique tuples right now.
#define MAX_IPMA_VERSION_AND_FLAGS_SEEN 4
// ---------------------------------------------------------------------------
// AVIF codec type (AV1 or AV2)
static avifCodecType avifGetCodecType(const uint8_t * fourcc)
{
if (!memcmp(fourcc, "av01", 4)) {
return AVIF_CODEC_TYPE_AV1;
}
#if defined(AVIF_CODEC_AVM)
if (!memcmp(fourcc, "av02", 4)) {
return AVIF_CODEC_TYPE_AV2;
}
#endif
return AVIF_CODEC_TYPE_UNKNOWN;
}
static const char * avifGetConfigurationPropertyName(avifCodecType codecType)
{
static const char kUnknown[] = "****";
switch (codecType) {
case AVIF_CODEC_TYPE_AV1:
return "av1C";
#if defined(AVIF_CODEC_AVM)
case AVIF_CODEC_TYPE_AV2:
return "av2C";
#endif
default:
assert(AVIF_FALSE);
return kUnknown; // Easier to deal with than NULL.
}
}
// ---------------------------------------------------------------------------
// Box data structures
typedef uint8_t avifBrand[4];
AVIF_ARRAY_DECLARE(avifBrandArray, avifBrand, brand);
// ftyp
typedef struct avifFileType
{
uint8_t majorBrand[4];
uint8_t minorVersion[4];
// If not null, points to a memory block of 4 * compatibleBrandsCount bytes.
const uint8_t * compatibleBrands;
int compatibleBrandsCount;
} avifFileType;
// ispe
typedef struct avifImageSpatialExtents
{
uint32_t width;
uint32_t height;
} avifImageSpatialExtents;
// auxC
typedef struct avifAuxiliaryType
{
char auxType[AUXTYPE_SIZE];
} avifAuxiliaryType;
// infe mime content_type
typedef struct avifContentType
{
char contentType[CONTENTTYPE_SIZE];
} avifContentType;
// colr
typedef struct avifColourInformationBox
{
avifBool hasICC;
uint64_t iccOffset;
size_t iccSize;
avifBool hasNCLX;
avifColorPrimaries colorPrimaries;
avifTransferCharacteristics transferCharacteristics;
avifMatrixCoefficients matrixCoefficients;
avifRange range;
} avifColourInformationBox;
#define MAX_PIXI_PLANE_DEPTHS 4
typedef struct avifPixelInformationProperty
{
uint8_t planeDepths[MAX_PIXI_PLANE_DEPTHS];
uint8_t planeCount;
#if defined(AVIF_ENABLE_EXPERIMENTAL_EXTENDED_PIXI)
avifBool hasExtendedFields; // The fields below were signaled if this is true.
uint8_t subsamplingFlag[MAX_PIXI_PLANE_DEPTHS]; // The fields below were signaled if this is true for a given channel.
uint8_t subsamplingType[MAX_PIXI_PLANE_DEPTHS];
uint8_t subsamplingLocation[MAX_PIXI_PLANE_DEPTHS];
#endif // AVIF_ENABLE_EXPERIMENTAL_EXTENDED_PIXI
} avifPixelInformationProperty;
typedef struct avifOperatingPointSelectorProperty
{
uint8_t opIndex;
} avifOperatingPointSelectorProperty;
typedef struct avifLayerSelectorProperty
{
uint16_t layerID;
} avifLayerSelectorProperty;
typedef struct avifAV1LayeredImageIndexingProperty
{
uint32_t layerSize[3];
} avifAV1LayeredImageIndexingProperty;
typedef struct avifOpaqueProperty
{
uint8_t usertype[16]; // Same as in avifImageItemProperty.
avifRWData boxPayload; // Same as in avifImageItemProperty.
} avifOpaqueProperty;
// Array of item or track ids.
AVIF_ARRAY_DECLARE(avifCodecEntityIDs, uint32_t, ids);
// Content of a box inside a 'grpl' box, representing a group of entities.
typedef struct avifEntityToGroup
{
uint8_t groupingType[4];
uint32_t groupID;
avifCodecEntityIDs entityIDs;
} avifEntityToGroup;
AVIF_ARRAY_DECLARE(avifEntityToGroups, avifEntityToGroup, groups);
// ---------------------------------------------------------------------------
// Top-level structures
struct avifMeta;
// Temporary storage for ipco/stsd contents until they can be associated and memcpy'd to an avifDecoderItem
typedef struct avifProperty
{
uint8_t type[4];
avifBool isOpaque;
union
{
avifImageSpatialExtents ispe;
avifAuxiliaryType auxC; // Contents of 'auxC' for items, or 'auxi' for tracks
avifColourInformationBox colr;
avifCodecConfigurationBox av1C; // TODO(yguyon): Rename or add av2C
avifPixelAspectRatioBox pasp;
avifCleanApertureBox clap;
avifImageRotation irot;
avifImageMirror imir;
avifPixelInformationProperty pixi;
avifOperatingPointSelectorProperty a1op;
avifLayerSelectorProperty lsel;
avifAV1LayeredImageIndexingProperty a1lx;
avifContentLightLevelInformationBox clli;
avifOpaqueProperty opaque;
} u;
} avifProperty;
AVIF_ARRAY_DECLARE(avifPropertyArray, avifProperty, prop);
// Finds the first property of a given type.
static const avifProperty * avifPropertyArrayFind(const avifPropertyArray * properties, const char * type)
{
for (uint32_t propertyIndex = 0; propertyIndex < properties->count; ++propertyIndex) {
const avifProperty * prop = &properties->prop[propertyIndex];
if (!memcmp(prop->type, type, 4)) {
return prop;
}
}
return NULL;
}
AVIF_ARRAY_DECLARE(avifExtentArray, avifExtent, extent);
// one "item" worth for decoding (all iref, iloc, iprp, etc refer to one of these)
typedef struct avifDecoderItem
{
uint32_t id;
struct avifMeta * meta; // Unowned; A back-pointer for convenience
uint8_t type[4];
size_t size;
avifBool idatStored; // If true, offset is relative to the associated meta box's idat box (iloc construction_method==1)
uint32_t width; // Set from this item's ispe property, if present
uint32_t height; // Set from this item's ispe property, if present
avifContentType contentType;
avifPropertyArray properties;
avifExtentArray extents; // All extent offsets/sizes
avifRWData mergedExtents; // if set, is a single contiguous block of this item's extents (unused when extents.count == 1)
avifBool ownsMergedExtents; // if true, mergedExtents must be freed when this item is destroyed
avifBool partialMergedExtents; // If true, mergedExtents doesn't have all of the item data yet
uint32_t thumbnailForID; // if non-zero, this item is a thumbnail for Item #{thumbnailForID}
uint32_t auxForID; // if non-zero, this item is an auxC plane for Item #{auxForID}
uint32_t descForID; // if non-zero, this item is a content description for Item #{descForID}
uint32_t dimgForID; // if non-zero, this item is an input of derived Item #{dimgForID}
uint32_t dimgIdx; // If dimgForId is non-zero, this is the zero-based index of this item in the list of Item #{dimgForID}'s dimg.
avifBool hasDimgFrom; // whether there is a 'dimg' box with this item's id as 'fromID'
uint32_t premByID; // if non-zero, this item is premultiplied by Item #{premByID}
avifBool hasUnsupportedEssentialProperty; // If true, this item cites a property flagged as 'essential' that libavif doesn't support (yet). Ignore the item, if so.
avifBool ipmaSeen; // if true, this item already received a property association
avifBool progressive; // if true, this item has progressive layers (a1lx), but does not select a specific layer (the layer_id value in lsel is set to 0xFFFF)
#if defined(AVIF_ENABLE_EXPERIMENTAL_MINI)
avifPixelFormat miniBoxPixelFormat; // Set from the MinimizedImageBox, if present (AVIF_PIXEL_FORMAT_NONE otherwise)
avifChromaSamplePosition miniBoxChromaSamplePosition; // Set from the MinimizedImageBox, if present (AVIF_CHROMA_SAMPLE_POSITION_UNKNOWN otherwise)
#endif
} avifDecoderItem;
AVIF_ARRAY_DECLARE(avifDecoderItemArray, avifDecoderItem *, item);
// grid storage
typedef struct avifImageGrid
{
uint32_t rows; // Legal range: [1-256]
uint32_t columns; // Legal range: [1-256]
uint32_t outputWidth;
uint32_t outputHeight;
} avifImageGrid;
// ---------------------------------------------------------------------------
// avifTrack
typedef struct avifSampleTableChunk
{
uint64_t offset;
} avifSampleTableChunk;
AVIF_ARRAY_DECLARE(avifSampleTableChunkArray, avifSampleTableChunk, chunk);
typedef struct avifSampleTableSampleToChunk
{
uint32_t firstChunk;
uint32_t samplesPerChunk;
uint32_t sampleDescriptionIndex;
} avifSampleTableSampleToChunk;
AVIF_ARRAY_DECLARE(avifSampleTableSampleToChunkArray, avifSampleTableSampleToChunk, sampleToChunk);
typedef struct avifSampleTableSampleSize
{
uint32_t size;
} avifSampleTableSampleSize;
AVIF_ARRAY_DECLARE(avifSampleTableSampleSizeArray, avifSampleTableSampleSize, sampleSize);
typedef struct avifSampleTableTimeToSample
{
uint32_t sampleCount;
uint32_t sampleDelta;
} avifSampleTableTimeToSample;
AVIF_ARRAY_DECLARE(avifSampleTableTimeToSampleArray, avifSampleTableTimeToSample, timeToSample);
typedef struct avifSyncSample
{
uint32_t sampleNumber;
} avifSyncSample;
AVIF_ARRAY_DECLARE(avifSyncSampleArray, avifSyncSample, syncSample);
typedef struct avifSampleDescription
{
uint8_t format[4];
avifPropertyArray properties;
} avifSampleDescription;
AVIF_ARRAY_DECLARE(avifSampleDescriptionArray, avifSampleDescription, description);
typedef struct avifSampleTable
{
avifSampleTableChunkArray chunks;
avifSampleDescriptionArray sampleDescriptions;
avifSampleTableSampleToChunkArray sampleToChunks;
avifSampleTableSampleSizeArray sampleSizes;
avifSampleTableTimeToSampleArray timeToSamples;
avifSyncSampleArray syncSamples;
uint32_t allSamplesSize; // If this is non-zero, sampleSizes will be empty and all samples will be this size
} avifSampleTable;
static void avifSampleTableDestroy(avifSampleTable * sampleTable);
static avifSampleTable * avifSampleTableCreate(void)
{
avifSampleTable * sampleTable = (avifSampleTable *)avifAlloc(sizeof(avifSampleTable));
if (sampleTable == NULL) {
return NULL;
}
memset(sampleTable, 0, sizeof(avifSampleTable));
if (!avifArrayCreate(&sampleTable->chunks, sizeof(avifSampleTableChunk), 16) ||
!avifArrayCreate(&sampleTable->sampleDescriptions, sizeof(avifSampleDescription), 2) ||
!avifArrayCreate(&sampleTable->sampleToChunks, sizeof(avifSampleTableSampleToChunk), 16) ||
!avifArrayCreate(&sampleTable->sampleSizes, sizeof(avifSampleTableSampleSize), 16) ||
!avifArrayCreate(&sampleTable->timeToSamples, sizeof(avifSampleTableTimeToSample), 16) ||
!avifArrayCreate(&sampleTable->syncSamples, sizeof(avifSyncSample), 16)) {
avifSampleTableDestroy(sampleTable);
return NULL;
}
return sampleTable;
}
static void avifPropertyArrayDestroy(avifPropertyArray * array)
{
for (size_t i = 0; i < array->count; ++i) {
if (array->prop[i].isOpaque) {
avifRWDataFree(&array->prop[i].u.opaque.boxPayload);
}
}
avifArrayDestroy(array);
}
static void avifSampleTableDestroy(avifSampleTable * sampleTable)
{
avifArrayDestroy(&sampleTable->chunks);
for (uint32_t i = 0; i < sampleTable->sampleDescriptions.count; ++i) {
avifSampleDescription * description = &sampleTable->sampleDescriptions.description[i];
avifPropertyArrayDestroy(&description->properties);
}
avifArrayDestroy(&sampleTable->sampleDescriptions);
avifArrayDestroy(&sampleTable->sampleToChunks);
avifArrayDestroy(&sampleTable->sampleSizes);
avifArrayDestroy(&sampleTable->timeToSamples);
avifArrayDestroy(&sampleTable->syncSamples);
avifFree(sampleTable);
}
static uint32_t avifSampleTableGetImageDelta(const avifSampleTable * sampleTable, uint32_t imageIndex)
{
uint32_t maxSampleIndex = 0;
for (uint32_t i = 0; i < sampleTable->timeToSamples.count; ++i) {
const avifSampleTableTimeToSample * timeToSample = &sampleTable->timeToSamples.timeToSample[i];
maxSampleIndex += timeToSample->sampleCount;
if ((imageIndex < maxSampleIndex) || (i == (sampleTable->timeToSamples.count - 1))) {
return timeToSample->sampleDelta;
}
}
// TODO: fail here?
return 1;
}
static avifCodecType avifSampleTableGetCodecType(const avifSampleTable * sampleTable)
{
for (uint32_t i = 0; i < sampleTable->sampleDescriptions.count; ++i) {
const avifCodecType codecType = avifGetCodecType(sampleTable->sampleDescriptions.description[i].format);
if (codecType != AVIF_CODEC_TYPE_UNKNOWN) {
return codecType;
}
}
return AVIF_CODEC_TYPE_UNKNOWN;
}
static uint32_t avifCodecConfigurationBoxGetDepth(const avifCodecConfigurationBox * av1C)
{
if (av1C->twelveBit) {
return 12;
} else if (av1C->highBitdepth) {
return 10;
}
return 8;
}
#if defined(AVIF_ENABLE_EXPERIMENTAL_EXTENDED_PIXI)
uint8_t avifCodecConfigurationBoxGetSubsamplingType(const avifCodecConfigurationBox * av1C, uint8_t channelIndex)
{
if (channelIndex == 0) {
return AVIF_PIXI_444;
}
if (av1C->chromaSubsamplingX == 0) {
if (av1C->chromaSubsamplingY == 0) {
return AVIF_PIXI_444;
}
return AVIF_PIXI_440;
}
if (av1C->chromaSubsamplingY == 0) {
return AVIF_PIXI_422;
}
return AVIF_PIXI_420;
}
// Mapping from PixelInformationBox subsampling_type and subsampling_location as defined in ISO/IEC 23008-12:2024/CDAM 2:2025 section 6.5.6.3
// to chroma_sample_position as defined in AV1 specification Section 6.4.2.
static uint8_t avifSubsamplingLocationToChromaSamplePosition(uint8_t subsamplingType, uint8_t subsamplingLocation)
{
if (subsamplingType == AVIF_PIXI_444) {
return AVIF_CHROMA_SAMPLE_POSITION_COLOCATED;
}
if (subsamplingType == AVIF_PIXI_422) {
if (subsamplingLocation == 0 || subsamplingLocation == 2 || subsamplingLocation == 4) {
return AVIF_CHROMA_SAMPLE_POSITION_COLOCATED;
}
}
if (subsamplingType == AVIF_PIXI_420) {
if (subsamplingLocation == 0) {
return AVIF_CHROMA_SAMPLE_POSITION_VERTICAL;
}
if (subsamplingLocation == 2) {
return AVIF_CHROMA_SAMPLE_POSITION_COLOCATED;
}
}
if (subsamplingType == AVIF_PIXI_411) {
if (subsamplingLocation == 0 || subsamplingLocation == 2 || subsamplingLocation == 4) {
return AVIF_CHROMA_SAMPLE_POSITION_COLOCATED;
}
}
if (subsamplingType == AVIF_PIXI_440) {
if (subsamplingLocation == 0 || subsamplingLocation == 1) {
return AVIF_CHROMA_SAMPLE_POSITION_VERTICAL;
}
if (subsamplingLocation == 2 || subsamplingLocation == 3) {
return AVIF_CHROMA_SAMPLE_POSITION_COLOCATED;
}
}
return AVIF_CHROMA_SAMPLE_POSITION_UNKNOWN;
}
#endif // AVIF_ENABLE_EXPERIMENTAL_EXTENDED_PIXI
static const avifPropertyArray * avifSampleTableGetProperties(const avifSampleTable * sampleTable, avifCodecType codecType)
{
for (uint32_t i = 0; i < sampleTable->sampleDescriptions.count; ++i) {
const avifSampleDescription * description = &sampleTable->sampleDescriptions.description[i];
if (avifGetCodecType(description->format) == codecType) {
return &description->properties;
}
}
return NULL;
}
// one video track ("trak" contents)
typedef struct avifTrack
{
uint32_t id;
uint8_t handlerType[4];
uint32_t auxForID; // if non-zero, this track is an auxC plane for Track #{auxForID}
uint32_t premByID; // if non-zero, this track is premultiplied by Track #{premByID}
uint32_t mediaTimescale;
uint64_t mediaDuration;
uint64_t trackDuration;
uint64_t segmentDuration;
avifBool isRepeating;
int repetitionCount;
uint32_t width;
uint32_t height;
avifSampleTable * sampleTable;
struct avifMeta * meta;
} avifTrack;
AVIF_ARRAY_DECLARE(avifTrackArray, avifTrack, track);
// ---------------------------------------------------------------------------
// avifCodecDecodeInput
avifCodecDecodeInput * avifCodecDecodeInputCreate(void)
{
avifCodecDecodeInput * decodeInput = (avifCodecDecodeInput *)avifAlloc(sizeof(avifCodecDecodeInput));
if (decodeInput == NULL) {
return NULL;
}
memset(decodeInput, 0, sizeof(avifCodecDecodeInput));
if (!avifArrayCreate(&decodeInput->samples, sizeof(avifDecodeSample), 1)) {
avifFree(decodeInput);
return NULL;
}
return decodeInput;
}
void avifCodecDecodeInputDestroy(avifCodecDecodeInput * decodeInput)
{
for (uint32_t sampleIndex = 0; sampleIndex < decodeInput->samples.count; ++sampleIndex) {
avifDecodeSample * sample = &decodeInput->samples.sample[sampleIndex];
if (sample->ownsData) {
avifRWDataFree((avifRWData *)&sample->data);
}
}
avifArrayDestroy(&decodeInput->samples);
avifFree(decodeInput);
}
// Returns how many samples are in the chunk.
static uint32_t avifGetSampleCountOfChunk(const avifSampleTableSampleToChunkArray * sampleToChunks, uint32_t chunkIndex)
{
uint32_t sampleCount = 0;
for (int sampleToChunkIndex = sampleToChunks->count - 1; sampleToChunkIndex >= 0; --sampleToChunkIndex) {
const avifSampleTableSampleToChunk * sampleToChunk = &sampleToChunks->sampleToChunk[sampleToChunkIndex];
if (sampleToChunk->firstChunk <= (chunkIndex + 1)) {
sampleCount = sampleToChunk->samplesPerChunk;
break;
}
}
return sampleCount;
}
static avifResult avifCodecDecodeInputFillFromSampleTable(avifCodecDecodeInput * decodeInput,
avifSampleTable * sampleTable,
const uint32_t imageCountLimit,
const uint64_t sizeHint,
avifDiagnostics * diag)
{
if (imageCountLimit) {
// Verify that the we're not about to exceed the frame count limit.
uint32_t imageCountLeft = imageCountLimit;
for (uint32_t chunkIndex = 0; chunkIndex < sampleTable->chunks.count; ++chunkIndex) {
// First, figure out how many samples are in this chunk
uint32_t sampleCount = avifGetSampleCountOfChunk(&sampleTable->sampleToChunks, chunkIndex);
if (sampleCount == 0) {
// chunks with 0 samples are invalid
avifDiagnosticsPrintf(diag, "Sample table contains a chunk with 0 samples");
return AVIF_RESULT_BMFF_PARSE_FAILED;
}
if (sampleCount > imageCountLeft) {
// This file exceeds the imageCountLimit, bail out
avifDiagnosticsPrintf(diag, "Exceeded avifDecoder's imageCountLimit");
return AVIF_RESULT_BMFF_PARSE_FAILED;
}
imageCountLeft -= sampleCount;
}
}
uint32_t sampleSizeIndex = 0;
for (uint32_t chunkIndex = 0; chunkIndex < sampleTable->chunks.count; ++chunkIndex) {
avifSampleTableChunk * chunk = &sampleTable->chunks.chunk[chunkIndex];
// First, figure out how many samples are in this chunk
uint32_t sampleCount = avifGetSampleCountOfChunk(&sampleTable->sampleToChunks, chunkIndex);
if (sampleCount == 0) {
// chunks with 0 samples are invalid
avifDiagnosticsPrintf(diag, "Sample table contains a chunk with 0 samples");
return AVIF_RESULT_BMFF_PARSE_FAILED;
}
uint64_t sampleOffset = chunk->offset;
for (uint32_t sampleIndex = 0; sampleIndex < sampleCount; ++sampleIndex) {
uint32_t sampleSize = sampleTable->allSamplesSize;
if (sampleSize == 0) {
if (sampleSizeIndex >= sampleTable->sampleSizes.count) {
// We've run out of samples to sum
avifDiagnosticsPrintf(diag, "Truncated sample table");
return AVIF_RESULT_BMFF_PARSE_FAILED;
}
avifSampleTableSampleSize * sampleSizePtr = &sampleTable->sampleSizes.sampleSize[sampleSizeIndex];
sampleSize = sampleSizePtr->size;
}
avifDecodeSample * sample = (avifDecodeSample *)avifArrayPush(&decodeInput->samples);
AVIF_CHECKERR(sample != NULL, AVIF_RESULT_OUT_OF_MEMORY);
sample->offset = sampleOffset;
sample->size = sampleSize;
sample->spatialID = AVIF_SPATIAL_ID_UNSET; // Not filtering by spatial_id
sample->sync = AVIF_FALSE; // to potentially be set to true following the outer loop
if (sampleSize > UINT64_MAX - sampleOffset) {
avifDiagnosticsPrintf(diag,
"Sample table contains an offset/size pair which overflows: [%" PRIu64 " / %u]",
sampleOffset,
sampleSize);
return AVIF_RESULT_BMFF_PARSE_FAILED;
}
if (sizeHint && ((sampleOffset + sampleSize) > sizeHint)) {
avifDiagnosticsPrintf(diag, "Exceeded avifIO's sizeHint, possibly truncated data");
return AVIF_RESULT_BMFF_PARSE_FAILED;
}
sampleOffset += sampleSize;
++sampleSizeIndex;
}
}
// Mark appropriate samples as sync
for (uint32_t syncSampleIndex = 0; syncSampleIndex < sampleTable->syncSamples.count; ++syncSampleIndex) {
uint32_t frameIndex = sampleTable->syncSamples.syncSample[syncSampleIndex].sampleNumber - 1; // sampleNumber is 1-based
if (frameIndex < decodeInput->samples.count) {
decodeInput->samples.sample[frameIndex].sync = AVIF_TRUE;
}
}
// Assume frame 0 is sync, just in case the stss box is absent in the BMFF. (Unnecessary?)
if (decodeInput->samples.count > 0) {
decodeInput->samples.sample[0].sync = AVIF_TRUE;
}
return AVIF_RESULT_OK;
}
static avifResult avifCodecDecodeInputFillFromDecoderItem(avifCodecDecodeInput * decodeInput,
avifDecoderItem * item,
avifBool allowProgressive,
const uint32_t imageCountLimit,
const uint64_t sizeHint,
avifDiagnostics * diag)
{
if (sizeHint && (item->size > sizeHint)) {
avifDiagnosticsPrintf(diag, "Exceeded avifIO's sizeHint, possibly truncated data");
return AVIF_RESULT_BMFF_PARSE_FAILED;
}
uint8_t layerCount = 0;
size_t layerSizes[4] = { 0 };
const avifProperty * a1lxProp = avifPropertyArrayFind(&item->properties, "a1lx");
if (a1lxProp) {
// Calculate layer count and all layer sizes from the a1lx box, and then validate
size_t remainingSize = item->size;
for (int i = 0; i < 3; ++i) {
++layerCount;
const size_t layerSize = (size_t)a1lxProp->u.a1lx.layerSize[i];
if (layerSize) {
if (layerSize >= remainingSize) { // >= instead of > because there must be room for the last layer
avifDiagnosticsPrintf(diag, "a1lx layer index [%d] does not fit in item size", i);
return AVIF_RESULT_BMFF_PARSE_FAILED;
}
layerSizes[i] = layerSize;
remainingSize -= layerSize;
} else {
layerSizes[i] = remainingSize;
remainingSize = 0;
break;
}
}
if (remainingSize > 0) {
AVIF_ASSERT_OR_RETURN(layerCount == 3);
++layerCount;
layerSizes[3] = remainingSize;
}
}
const avifProperty * lselProp = avifPropertyArrayFind(&item->properties, "lsel");
// Progressive images offer layers via the a1lxProp, but don't specify a layer selection with lsel.
//
// For backward compatibility with earlier drafts of AVIF spec v1.1.0, treat an absent lsel as
// equivalent to layer_id == 0xFFFF during the transitional period. Remove !lselProp when the test
// images have been updated to the v1.1.0 spec.
item->progressive = (a1lxProp && (!lselProp || (lselProp->u.lsel.layerID == 0xFFFF)));
if (lselProp && (lselProp->u.lsel.layerID != 0xFFFF)) {
// Layer selection. This requires that the underlying AV1 codec decodes all layers,
// and then only returns the requested layer as a single frame. To the user of libavif,
// this appears to be a single frame.
decodeInput->allLayers = AVIF_TRUE;
size_t sampleSize = 0;
if (layerCount > 0) {
// Optimization: If we're selecting a layer that doesn't require the entire image's payload (hinted via the a1lx box)
if (lselProp->u.lsel.layerID >= layerCount) {
avifDiagnosticsPrintf(diag,
"lsel property requests layer index [%u] which isn't present in a1lx property ([%u] layers)",
lselProp->u.lsel.layerID,
layerCount);
return AVIF_RESULT_BMFF_PARSE_FAILED;
}
for (uint8_t i = 0; i <= lselProp->u.lsel.layerID; ++i) {
sampleSize += layerSizes[i];
}
} else {
// This layer's payload subsection is unknown, just use the whole payload
sampleSize = item->size;
}
avifDecodeSample * sample = (avifDecodeSample *)avifArrayPush(&decodeInput->samples);
AVIF_CHECKERR(sample != NULL, AVIF_RESULT_OUT_OF_MEMORY);
sample->itemID = item->id;
sample->offset = 0;
sample->size = sampleSize;
AVIF_ASSERT_OR_RETURN(lselProp->u.lsel.layerID < AVIF_MAX_AV1_LAYER_COUNT);
sample->spatialID = (uint8_t)lselProp->u.lsel.layerID;
sample->sync = AVIF_TRUE;
} else if (allowProgressive && item->progressive) {
// Progressive image. Decode all layers and expose them all to the user.
if (imageCountLimit && (layerCount > imageCountLimit)) {
avifDiagnosticsPrintf(diag, "Exceeded avifDecoder's imageCountLimit (progressive)");
return AVIF_RESULT_BMFF_PARSE_FAILED;
}
decodeInput->allLayers = AVIF_TRUE;
size_t offset = 0;
for (int i = 0; i < layerCount; ++i) {
avifDecodeSample * sample = (avifDecodeSample *)avifArrayPush(&decodeInput->samples);
AVIF_CHECKERR(sample != NULL, AVIF_RESULT_OUT_OF_MEMORY);
sample->itemID = item->id;
sample->offset = offset;
sample->size = layerSizes[i];
sample->spatialID = AVIF_SPATIAL_ID_UNSET;
sample->sync = (i == 0); // Assume all layers depend on the first layer
offset += layerSizes[i];
}
} else {
// Typical case: Use the entire item's payload for a single frame output
avifDecodeSample * sample = (avifDecodeSample *)avifArrayPush(&decodeInput->samples);
AVIF_CHECKERR(sample != NULL, AVIF_RESULT_OUT_OF_MEMORY);
sample->itemID = item->id;
sample->offset = 0;
sample->size = item->size;
sample->spatialID = AVIF_SPATIAL_ID_UNSET;
sample->sync = AVIF_TRUE;
}
return AVIF_RESULT_OK;
}
// ---------------------------------------------------------------------------
// Helper macros / functions
#define BEGIN_STREAM(VARNAME, PTR, SIZE, DIAG, CONTEXT) \
avifROStream VARNAME; \
avifROData VARNAME##_roData; \
VARNAME##_roData.data = PTR; \
VARNAME##_roData.size = SIZE; \
avifROStreamStart(&VARNAME, &VARNAME##_roData, DIAG, CONTEXT)
typedef enum avifUniqueBoxFlag
{
AVIF_UNIQUE_ILOC = 0,
AVIF_UNIQUE_PITM,
AVIF_UNIQUE_IDAT,
AVIF_UNIQUE_IPRP,
AVIF_UNIQUE_IINF,
AVIF_UNIQUE_IREF,
AVIF_UNIQUE_GRPL,
} avifUniqueBoxFlag;
// Use this to keep track of whether or not a child box that must be unique (0 or 1 present) has
// been seen yet, when parsing a parent box. If the "seen" bit is already set for a given box when
// it is encountered during parse, an error is thrown. Which bit corresponds to which box is
// dictated entirely by the calling function.
static avifBool uniqueBoxSeen(uint32_t * uniqueBoxFlags,
avifUniqueBoxFlag whichFlag,
const char * parentBoxType,
const char * boxType,
avifDiagnostics * diagnostics)
{
const uint32_t flag = 1 << whichFlag;
if (*uniqueBoxFlags & flag) {
// This box has already been seen. Error!
avifDiagnosticsPrintf(diagnostics, "Box[%s] contains a duplicate unique box of type '%s'", parentBoxType, boxType);
return AVIF_FALSE;
}
// Mark this box as seen.
*uniqueBoxFlags |= flag;
return AVIF_TRUE;
}
// ---------------------------------------------------------------------------
// avifDecoderData
typedef struct avifTile
{
avifCodecDecodeInput * input;
avifCodecType codecType;
// This may point to a codec that it owns or point to a shared codec that it does not own. In the shared case, this will
// point to one of the avifCodec instances in avifDecoderData.
struct avifCodec * codec;
avifImage * image;
uint32_t width; // Either avifTrack.width or avifDecoderItem.width
uint32_t height; // Either avifTrack.height or avifDecoderItem.height
uint8_t operatingPoint;
} avifTile;
AVIF_ARRAY_DECLARE(avifTileArray, avifTile, tile);
// This holds one "meta" box (from the BMFF and HEIF standards) worth of relevant-to-AVIF information.
// * If a meta box is parsed from the root level of the BMFF, it can contain the information about
// "items" which might be color planes, alpha planes, or EXIF or XMP metadata.
// * If a meta box is parsed from inside of a track ("trak") box, any metadata (EXIF/XMP) items inside
// of that box are implicitly associated with that track.
typedef struct avifMeta
{
// Items (from HEIF) are the generic storage for any data that does not require timed processing
// (single image color planes, alpha planes, EXIF, XMP, etc). Each item has a unique integer ID >1,
// and is defined by a series of child boxes in a meta box:
// * iloc - location: byte offset to item data, item size in bytes
// * iinf - information: type of item (color planes, alpha plane, EXIF, XMP)
// * ipco - properties: dimensions, aspect ratio, image transformations, references to other items
// * ipma - associations: Attaches an item in the properties list to a given item
//
// Items are lazily created in this array when any of the above boxes refer to one by a new (unseen) ID,
// and are then further modified/updated as new information for an item's ID is parsed.
avifDecoderItemArray items;
// Any ipco boxes explained above are populated into this array as a staging area, which are
// then duplicated into the appropriate items upon encountering an item property association
// (ipma) box.
avifPropertyArray properties;
// Filled with the contents of this meta box's "idat" box, which is raw data that an item can
// directly refer to in its item location box (iloc) instead of just giving an offset into the
// overall file. If all items' iloc boxes simply point at an offset/length in the file itself,
// this buffer will likely be empty.
avifRWData idat;
// Ever-incrementing ID for uniquely identifying which 'meta' box contains an idat (when
// multiple meta boxes exist as BMFF siblings). Each time avifParseMetaBox() is called on an
// avifMeta struct, this value is incremented. Any time an additional meta box is detected at
// the same "level" (root level, trak level, etc), this ID helps distinguish which meta box's
// "idat" is which, as items implicitly reference idat boxes that exist in the same meta
// box.
uint32_t idatID;
// Contents of a pitm box, which signal which of the items in this file is the main image. For
// AVIF, this should point at an image item containing color planes, and all other items
// are ignored unless they refer to this item in some way (alpha plane, EXIF/XMP metadata).
uint32_t primaryItemID;
// Contents of grpl box, which signal groups of entities (items or tracks).
avifEntityToGroups entityToGroups;
// Parsed from Sample Transform metadata if present, otherwise empty.
avifSampleTransformExpression sampleTransformExpression;
// Bit depth extracted from the pixi property of the Sample Transform derived image item, if any.
uint32_t sampleTransformDepth;
#if defined(AVIF_ENABLE_EXPERIMENTAL_MINI)
// If true, the fields above were extracted from a MinimizedImageBox.
avifBool fromMiniBox;
#endif
} avifMeta;
static void avifMetaDestroy(avifMeta * meta);
static avifMeta * avifMetaCreate(void)
{
avifMeta * meta = (avifMeta *)avifAlloc(sizeof(avifMeta));
if (meta == NULL) {
return NULL;
}
memset(meta, 0, sizeof(avifMeta));
if (!avifArrayCreate(&meta->items, sizeof(avifDecoderItem *), 8) || !avifArrayCreate(&meta->properties, sizeof(avifProperty), 16) ||
!avifArrayCreate(&meta->entityToGroups, sizeof(avifEntityToGroup), 1)) {
avifMetaDestroy(meta);
return NULL;
}
return meta;
}
static void avifMetaDestroy(avifMeta * meta)
{
for (uint32_t i = 0; i < meta->items.count; ++i) {
avifDecoderItem * item = meta->items.item[i];
avifPropertyArrayDestroy(&item->properties);
avifArrayDestroy(&item->extents);
if (item->ownsMergedExtents) {
avifRWDataFree(&item->mergedExtents);
}
avifFree(item);
}
avifArrayDestroy(&meta->items);
avifPropertyArrayDestroy(&meta->properties);
avifRWDataFree(&meta->idat);
avifArrayDestroy(&meta->sampleTransformExpression);
for (uint32_t i = 0; i < meta->entityToGroups.count; ++i) {
avifArrayDestroy(&meta->entityToGroups.groups[i].entityIDs);
}
avifArrayDestroy(&meta->entityToGroups);
avifFree(meta);
}
static avifResult avifCheckItemID(const char * boxFourcc, uint32_t itemID, avifDiagnostics * diag)
{
// Section 8.11.1.1 of ISO/IEC 14496-12 about MetaBox definition:
// The item_ID value of 0 should not be used
// Section 8.11.6 of ISO/IEC 14496-12 about ItemInfoEntry syntax and semantics:
// item_ID contains either 0 for the primary resource (e.g. the XML contained in an XMLBox)
// or the ID of the item for which the following information is defined.
// Assuming 'infe' is the only way to properly define an item in AVIF, a compliant item cannot have an ID of zero.
// One way to bypass that rule would be to have 'infe' with item_ID being 0, referring to "the primary resource",
// and 'pitm' defining "the primary resource" as the item with an item_ID of 0. libavif considers that as invalid.
if (itemID == 0) {
avifDiagnosticsPrintf(diag, "Box[%.4s] has an invalid item ID [%u]", boxFourcc, itemID);
return AVIF_RESULT_BMFF_PARSE_FAILED;
}
return AVIF_RESULT_OK;
}
static avifResult avifMetaFindOrCreateItem(avifMeta * meta, uint32_t itemID, avifDecoderItem ** item)
{
*item = NULL;
AVIF_ASSERT_OR_RETURN(itemID != 0);
for (uint32_t i = 0; i < meta->items.count; ++i) {
if (meta->items.item[i]->id == itemID) {
*item = meta->items.item[i];
return AVIF_RESULT_OK;
}
}
avifDecoderItem ** itemPtr = (avifDecoderItem **)avifArrayPush(&meta->items);
AVIF_CHECKERR(itemPtr != NULL, AVIF_RESULT_OUT_OF_MEMORY);
*item = (avifDecoderItem *)avifAlloc(sizeof(avifDecoderItem));
if (*item == NULL) {
avifArrayPop(&meta->items);
return AVIF_RESULT_OUT_OF_MEMORY;
}
memset(*item, 0, sizeof(avifDecoderItem));
*itemPtr = *item;
if (!avifArrayCreate(&(*item)->properties, sizeof(avifProperty), 16)) {
avifFree(*item);
*item = NULL;
avifArrayPop(&meta->items);
return AVIF_RESULT_OUT_OF_MEMORY;
}
if (!avifArrayCreate(&(*item)->extents, sizeof(avifExtent), 1)) {
avifPropertyArrayDestroy(&(*item)->properties);
avifFree(*item);
*item = NULL;
avifArrayPop(&meta->items);
return AVIF_RESULT_OUT_OF_MEMORY;
}
(*item)->id = itemID;
(*item)->meta = meta;
return AVIF_RESULT_OK;
}
// A group of AVIF tiles in an image item, such as a single tile or a grid of multiple tiles.
typedef struct avifTileInfo
{
unsigned int tileCount;
unsigned int decodedTileCount;
unsigned int firstTileIndex; // Within avifDecoderData.tiles.
avifImageGrid grid;
} avifTileInfo;
typedef struct avifDecoderData
{
avifMeta * meta; // The root-level meta box
avifTrackArray tracks;
avifTileArray tiles;
avifTileInfo tileInfos[AVIF_ITEM_CATEGORY_COUNT];
avifDecoderSource source;
// When decoding AVIF images with grid, use a single decoder instance for all the tiles instead of creating a decoder instance
// for each tile. If that is the case, |codec| will be used by all the tiles.
//
// There are some edge cases where we will still need multiple decoder instances:
// * For animated AVIF with alpha, we will need two instances (one for the color planes and one for the alpha plane since they are both
// encoded as separate video sequences). In this case, |codec| will be used for the color planes and |codecAlpha| will be
// used for the alpha plane.
// * For grid images with multiple layers. In this case, each tile will need its own decoder instance since there would be
// multiple layers in each tile. In this case, |codec| and |codecAlpha| are not used and each tile will have its own
// decoder instance.
// * For grid images where the operating points of all the tiles are not the same. In this case, each tile needs its own
// decoder instance (same as above).
avifCodec * codec;
avifCodec * codecAlpha;
uint8_t majorBrand[4]; // From the file's ftyp, used by AVIF_DECODER_SOURCE_AUTO
avifBrandArray compatibleBrands; // From the file's ftyp
avifDiagnostics * diag; // Shallow copy; owned by avifDecoder
const avifSampleTable * sourceSampleTable; // NULL unless (source == AVIF_DECODER_SOURCE_TRACKS), owned by an avifTrack
avifBool cicpSet; // True if avifDecoder's image has had its CICP set correctly yet.
// This allows nclx colr boxes to override AV1 CICP, as specified in the MIAF
// standard (ISO/IEC 23000-22:2019), section 7.3.6.4:
// The colour information property takes precedence over any colour information
// in the image bitstream, i.e. if the property is present, colour information in
// the bitstream shall be ignored.
// Remember the dimg association order to the Sample Transform derived image item.
// Colour items only. The alpha items are implicit.
uint8_t sampleTransformNumInputImageItems; // At most AVIF_SAMPLE_TRANSFORM_MAX_NUM_INPUT_IMAGE_ITEMS.
avifItemCategory sampleTransformInputImageItems[AVIF_SAMPLE_TRANSFORM_MAX_NUM_INPUT_IMAGE_ITEMS];
} avifDecoderData;
static void avifDecoderDataDestroy(avifDecoderData * data);
static avifDecoderData * avifDecoderDataCreate(void)
{
avifDecoderData * data = (avifDecoderData *)avifAlloc(sizeof(avifDecoderData));
if (data == NULL) {
return NULL;
}
memset(data, 0, sizeof(avifDecoderData));
data->meta = avifMetaCreate();
if (data->meta == NULL || !avifArrayCreate(&data->tracks, sizeof(avifTrack), 2) ||
!avifArrayCreate(&data->tiles, sizeof(avifTile), 8)) {
avifDecoderDataDestroy(data);
return NULL;
}
return data;
}
static void avifDecoderDataResetCodec(avifDecoderData * data)
{
for (unsigned int i = 0; i < data->tiles.count; ++i) {
avifTile * tile = &data->tiles.tile[i];
if (tile->image) {
avifImageFreePlanes(tile->image, AVIF_PLANES_ALL); // forget any pointers into codec image buffers
}
if (tile->codec) {
// Check if tile->codec was created separately and destroy it in that case.
if (tile->codec != data->codec && tile->codec != data->codecAlpha) {
avifCodecDestroy(tile->codec);
}
tile->codec = NULL;
}
}
for (int c = 0; c < AVIF_ITEM_CATEGORY_COUNT; ++c) {
data->tileInfos[c].decodedTileCount = 0;
}
if (data->codec) {
avifCodecDestroy(data->codec);
data->codec = NULL;
}
if (data->codecAlpha) {
avifCodecDestroy(data->codecAlpha);
data->codecAlpha = NULL;
}
}
static avifTile * avifDecoderDataCreateTile(avifDecoderData * data, avifCodecType codecType, uint32_t width, uint32_t height, uint8_t operatingPoint)
{
avifTile * tile = (avifTile *)avifArrayPush(&data->tiles);
if (tile == NULL) {
return NULL;
}
tile->codecType = codecType;
tile->image = avifImageCreateEmpty();
if (!tile->image) {
goto error;
}
tile->input = avifCodecDecodeInputCreate();
if (!tile->input) {
goto error;
}
tile->width = width;
tile->height = height;
tile->operatingPoint = operatingPoint;
return tile;
error:
if (tile->input) {
avifCodecDecodeInputDestroy(tile->input);
}
if (tile->image) {
avifImageDestroy(tile->image);
}
avifArrayPop(&data->tiles);
return NULL;
}
static avifTrack * avifDecoderDataCreateTrack(avifDecoderData * data)
{
avifTrack * track = (avifTrack *)avifArrayPush(&data->tracks);
if (track == NULL) {
return NULL;
}
track->meta = avifMetaCreate();
if (track->meta == NULL) {
avifArrayPop(&data->tracks);
return NULL;
}
return track;
}
static void avifDecoderDataClearTiles(avifDecoderData * data)
{
for (unsigned int i = 0; i < data->tiles.count; ++i) {
avifTile * tile = &data->tiles.tile[i];
if (tile->input) {
avifCodecDecodeInputDestroy(tile->input);
tile->input = NULL;
}
if (tile->codec) {
// Check if tile->codec was created separately and destroy it in that case.
if (tile->codec != data->codec && tile->codec != data->codecAlpha) {
avifCodecDestroy(tile->codec);
}
tile->codec = NULL;
}
if (tile->image) {
avifImageDestroy(tile->image);
tile->image = NULL;
}
}
data->tiles.count = 0;
for (int c = 0; c < AVIF_ITEM_CATEGORY_COUNT; ++c) {
data->tileInfos[c].tileCount = 0;
data->tileInfos[c].decodedTileCount = 0;
}
if (data->codec) {
avifCodecDestroy(data->codec);
data->codec = NULL;
}
if (data->codecAlpha) {
avifCodecDestroy(data->codecAlpha);
data->codecAlpha = NULL;
}
}
static void avifDecoderDataDestroy(avifDecoderData * data)
{
if (data->meta) {
avifMetaDestroy(data->meta);
}
for (uint32_t i = 0; i < data->tracks.count; ++i) {
avifTrack * track = &data->tracks.track[i];
if (track->sampleTable) {
avifSampleTableDestroy(track->sampleTable);
}
if (track->meta) {
avifMetaDestroy(track->meta);
}
}
avifArrayDestroy(&data->tracks);
avifDecoderDataClearTiles(data);
avifArrayDestroy(&data->tiles);
avifArrayDestroy(&data->compatibleBrands);
avifFree(data);
}
// This returns the max extent that has to be read in order to decode this item. If
// the item is stored in an idat, the data has already been read during Parse() and
// this function will return AVIF_RESULT_OK with a 0-byte extent.
static avifResult avifDecoderItemMaxExtent(const avifDecoderItem * item, const avifDecodeSample * sample, avifExtent * outExtent)
{
if (item->extents.count == 0) {
return AVIF_RESULT_TRUNCATED_DATA;
}
if (item->idatStored) {
// construction_method: idat(1)
if (item->meta->idat.size > 0) {
// Already read from a meta box during Parse()
memset(outExtent, 0, sizeof(avifExtent));
return AVIF_RESULT_OK;
}
// no associated idat box was found in the meta box, bail out
return AVIF_RESULT_NO_CONTENT;
}
// construction_method: file(0)
if (sample->size == 0) {
return AVIF_RESULT_TRUNCATED_DATA;
}
uint64_t remainingOffset = sample->offset;
size_t remainingBytes = sample->size; // This may be smaller than item->size if the item is progressive
// Assert that the for loop below will execute at least one iteration.
AVIF_ASSERT_OR_RETURN(item->extents.count != 0);
uint64_t minOffset = UINT64_MAX;
uint64_t maxOffset = 0;
for (uint32_t extentIter = 0; extentIter < item->extents.count; ++extentIter) {
avifExtent * extent = &item->extents.extent[extentIter];
// Make local copies of extent->offset and extent->size as they might need to be adjusted
// due to the sample's offset.
uint64_t startOffset = extent->offset;
size_t extentSize = extent->size;
if (remainingOffset) {
if (remainingOffset >= extentSize) {
remainingOffset -= extentSize;
continue;
} else {
if (remainingOffset > UINT64_MAX - startOffset) {
return AVIF_RESULT_BMFF_PARSE_FAILED;
}
startOffset += remainingOffset;
extentSize -= (size_t)remainingOffset;
remainingOffset = 0;
}
}
const size_t usedExtentSize = (extentSize < remainingBytes) ? extentSize : remainingBytes;
if (usedExtentSize > UINT64_MAX - startOffset) {
return AVIF_RESULT_BMFF_PARSE_FAILED;
}
const uint64_t endOffset = startOffset + usedExtentSize;
if (minOffset > startOffset) {
minOffset = startOffset;
}
if (maxOffset < endOffset) {
maxOffset = endOffset;
}
remainingBytes -= usedExtentSize;
if (remainingBytes == 0) {
// We've got enough bytes for this sample.
break;
}
}
if (remainingBytes != 0) {
return AVIF_RESULT_TRUNCATED_DATA;
}
outExtent->offset = minOffset;
const uint64_t extentLength = maxOffset - minOffset;
#if UINT64_MAX > SIZE_MAX
if (extentLength > SIZE_MAX) {
return AVIF_RESULT_BMFF_PARSE_FAILED;
}
#endif
outExtent->size = (size_t)extentLength;
return AVIF_RESULT_OK;
}
static uint8_t avifDecoderItemOperatingPoint(const avifDecoderItem * item)
{
const avifProperty * a1opProp = avifPropertyArrayFind(&item->properties, "a1op");
if (a1opProp) {
return a1opProp->u.a1op.opIndex;
}
return 0; // default
}
static avifResult avifDecoderItemValidateProperties(const avifDecoderItem * item,
const char * configPropName,
avifDiagnostics * diag,
const avifStrictFlags strictFlags)
{
const avifProperty * const configProp = avifPropertyArrayFind(&item->properties, configPropName);
if (!configProp) {
// An item configuration property box is mandatory in all valid AVIF configurations. Bail out.
avifDiagnosticsPrintf(diag, "Item ID %u of type '%.4s' is missing mandatory %s property", item->id, (const char *)item->type, configPropName);
return AVIF_RESULT_BMFF_PARSE_FAILED;
}
if (!memcmp(item->type, "grid", 4)) {
for (uint32_t i = 0; i < item->meta->items.count; ++i) {
avifDecoderItem * tile = item->meta->items.item[i];
if (tile->dimgForID != item->id) {
continue;
}
// Tile item types were checked in avifDecoderGenerateImageTiles(), no need to do it here.
// MIAF (ISO 23000-22:2019), Section 7.3.11.4.1:
// All input images of a grid image item shall use the same [...] chroma sampling format,
// and the same decoder configuration (see 7.3.6.2).
// The chroma sampling format is part of the decoder configuration.
const avifProperty * tileConfigProp = avifPropertyArrayFind(&tile->properties, configPropName);
if (!tileConfigProp) {
avifDiagnosticsPrintf(diag,
"Tile item ID %u of type '%.4s' is missing mandatory %s property",
tile->id,
(const char *)tile->type,
configPropName);
return AVIF_RESULT_BMFF_PARSE_FAILED;
}
// configProp was copied from a tile item to the grid item. Comparing tileConfigProp with it
// is equivalent to comparing tileConfigProp with the configPropName from the first tile.
if ((tileConfigProp->u.av1C.seqProfile != configProp->u.av1C.seqProfile) ||
(tileConfigProp->u.av1C.seqLevelIdx0 != configProp->u.av1C.seqLevelIdx0) ||
(tileConfigProp->u.av1C.seqTier0 != configProp->u.av1C.seqTier0) ||
(tileConfigProp->u.av1C.highBitdepth != configProp->u.av1C.highBitdepth) ||
(tileConfigProp->u.av1C.twelveBit != configProp->u.av1C.twelveBit) ||
(tileConfigProp->u.av1C.monochrome != configProp->u.av1C.monochrome) ||
(tileConfigProp->u.av1C.chromaSubsamplingX != configProp->u.av1C.chromaSubsamplingX) ||
(tileConfigProp->u.av1C.chromaSubsamplingY != configProp->u.av1C.chromaSubsamplingY) ||
(tileConfigProp->u.av1C.chromaSamplePosition != configProp->u.av1C.chromaSamplePosition)) {
avifDiagnosticsPrintf(diag,
"The fields of the %s property of tile item ID %u of type '%.4s' differs from other tiles",
configPropName,
tile->id,
(const char *)tile->type);
return AVIF_RESULT_BMFF_PARSE_FAILED;
}
}
}
const avifProperty * pixiProp = avifPropertyArrayFind(&item->properties, "pixi");
if (!pixiProp && (strictFlags & AVIF_STRICT_PIXI_REQUIRED)) {
// A pixi box is mandatory in all valid AVIF configurations. Bail out.
avifDiagnosticsPrintf(diag,
"[Strict] Item ID %u of type '%.4s' is missing mandatory pixi property",
item->id,
(const char *)item->type);
return AVIF_RESULT_BMFF_PARSE_FAILED;
}
if (pixiProp) {
const uint32_t configDepth = avifCodecConfigurationBoxGetDepth(&configProp->u.av1C);
for (uint8_t i = 0; i < pixiProp->u.pixi.planeCount; ++i) {
if (pixiProp->u.pixi.planeDepths[i] != configDepth) {
// pixi depth must match configuration property depth
avifDiagnosticsPrintf(diag,
"Item ID %u depth specified by pixi property [%u] does not match %s property depth [%u]",
item->id,
pixiProp->u.pixi.planeDepths[i],
configPropName,
configDepth);
return AVIF_RESULT_BMFF_PARSE_FAILED;
}
#if defined(AVIF_ENABLE_EXPERIMENTAL_EXTENDED_PIXI)
if (pixiProp->u.pixi.subsamplingFlag[i]) {
if (pixiProp->u.pixi.subsamplingType[i] != avifCodecConfigurationBoxGetSubsamplingType(&configProp->u.av1C, i)) {
avifDiagnosticsPrintf(diag,
"Item ID %u subsampling type specified by pixi property [%u] for channel %u does not match %s property [%u,%u]",
item->id,
pixiProp->u.pixi.subsamplingType[i],
i,
configPropName,
configProp->u.av1C.chromaSubsamplingX,
configProp->u.av1C.chromaSubsamplingY);
return AVIF_RESULT_BMFF_PARSE_FAILED;
}
if (configProp->u.av1C.chromaSamplePosition != AVIF_CHROMA_SAMPLE_POSITION_UNKNOWN) {
const avifChromaSamplePosition expectedChromaSamplePosition =
i == AVIF_CHAN_Y ? AVIF_CHROMA_SAMPLE_POSITION_COLOCATED : configProp->u.av1C.chromaSamplePosition;
if (avifSubsamplingLocationToChromaSamplePosition(pixiProp->u.pixi.subsamplingType[i],
pixiProp->u.pixi.subsamplingLocation[i]) !=
expectedChromaSamplePosition) {
avifDiagnosticsPrintf(diag,
"Item ID %u subsampling type and location specified by pixi property [%u,%u] for channel %u does not match %s property chroma sample position [%u]",
item->id,
pixiProp->u.pixi.subsamplingType[i],
pixiProp->u.pixi.subsamplingLocation[i],
i,
configPropName,
configProp->u.av1C.chromaSamplePosition);
return AVIF_RESULT_BMFF_PARSE_FAILED;
}
}
}
#endif // AVIF_ENABLE_EXPERIMENTAL_EXTENDED_PIXI
}
}
#if defined(AVIF_ENABLE_EXPERIMENTAL_MINI)
if (item->miniBoxPixelFormat != AVIF_PIXEL_FORMAT_NONE) {
// This is a MinimizedImageBox ('mini').
avifPixelFormat av1CPixelFormat;
if (configProp->u.av1C.monochrome) {
av1CPixelFormat = AVIF_PIXEL_FORMAT_YUV400;
} else if (configProp->u.av1C.chromaSubsamplingY == 1) {
av1CPixelFormat = AVIF_PIXEL_FORMAT_YUV420;
} else if (configProp->u.av1C.chromaSubsamplingX == 1) {
av1CPixelFormat = AVIF_PIXEL_FORMAT_YUV422;
} else {
av1CPixelFormat = AVIF_PIXEL_FORMAT_YUV444;
}
if (item->miniBoxPixelFormat != av1CPixelFormat) {
avifDiagnosticsPrintf(diag,
"Item ID %u format [%s] specified by MinimizedImageBox does not match %s property format [%s]",
item->id,
avifPixelFormatToString(item->miniBoxPixelFormat),
configPropName,
avifPixelFormatToString(av1CPixelFormat));
return AVIF_RESULT_BMFF_PARSE_FAILED;
}
if (configProp->u.av1C.chromaSamplePosition == /*CSP_UNKNOWN=*/0) {
// Section 6.4.2. Color config semantics of AV1 specification says:
// CSP_UNKNOWN - the source video transfer function must be signaled outside the AV1 bitstream
// See https://aomediacodec.github.io/av1-spec/#color-config-semantics
// So item->miniBoxChromaSamplePosition can differ and will override the AV1 value.
} else if ((uint8_t)item->miniBoxChromaSamplePosition != configProp->u.av1C.chromaSamplePosition) {
avifDiagnosticsPrintf(diag,
"Item ID %u chroma sample position [%u] specified by MinimizedImageBox does not match %s property chroma sample position [%u]",
item->id,
(uint32_t)item->miniBoxChromaSamplePosition,
configPropName,
configProp->u.av1C.chromaSamplePosition);
return AVIF_RESULT_BMFF_PARSE_FAILED;
}
}
#endif // AVIF_ENABLE_EXPERIMENTAL_MINI
if (strictFlags & AVIF_STRICT_CLAP_VALID) {
const avifProperty * clapProp = avifPropertyArrayFind(&item->properties, "clap");
if (clapProp) {
const avifProperty * ispeProp = avifPropertyArrayFind(&item->properties, "ispe");
if (!ispeProp) {
avifDiagnosticsPrintf(diag,
"[Strict] Item ID %u is missing an ispe property, so its clap property cannot be validated",
item->id);
return AVIF_RESULT_BMFF_PARSE_FAILED;
}
avifCropRect cropRect;
const uint32_t imageW = ispeProp->u.ispe.width;
const uint32_t imageH = ispeProp->u.ispe.height;
const avifBool validClap = avifCropRectFromCleanApertureBox(&cropRect, &clapProp->u.clap, imageW, imageH, diag);
if (!validClap) {
return AVIF_RESULT_BMFF_PARSE_FAILED;
}
}
}
return AVIF_RESULT_OK;
}
static avifResult avifDecoderItemRead(avifDecoderItem * item,
avifIO * io,
avifROData * outData,
size_t offset,
size_t partialByteCount,
avifDiagnostics * diag)
{
if (item->mergedExtents.data && !item->partialMergedExtents) {
// Multiple extents have already been concatenated for this item, just return it
if (offset >= item->mergedExtents.size) {
avifDiagnosticsPrintf(diag, "Item ID %u read has overflowing offset", item->id);
return AVIF_RESULT_TRUNCATED_DATA;
}
outData->data = item->mergedExtents.data + offset;
outData->size = item->mergedExtents.size - offset;
return AVIF_RESULT_OK;
}
if (item->extents.count == 0) {
avifDiagnosticsPrintf(diag, "Item ID %u has zero extents", item->id);
return AVIF_RESULT_TRUNCATED_DATA;
}
// Find this item's source of all extents' data, based on the construction method
const avifRWData * idatBuffer = NULL;
if (item->idatStored) {
// construction_method: idat(1)
if (item->meta->idat.size > 0) {
idatBuffer = &item->meta->idat;
} else {
// no associated idat box was found in the meta box, bail out
avifDiagnosticsPrintf(diag, "Item ID %u is stored in an idat, but no associated idat box was found", item->id);
return AVIF_RESULT_NO_CONTENT;
}
}
// Merge extents into a single contiguous buffer
if ((io->sizeHint > 0) && (item->size > io->sizeHint)) {
// Sanity check: somehow the sum of extents exceeds the entire file or idat size!
avifDiagnosticsPrintf(diag, "Item ID %u reported size failed size hint sanity check. Truncated data?", item->id);
return AVIF_RESULT_TRUNCATED_DATA;
}
if (offset >= item->size) {
avifDiagnosticsPrintf(diag, "Item ID %u read has overflowing offset", item->id);
return AVIF_RESULT_TRUNCATED_DATA;
}
const size_t maxOutputSize = item->size - offset;
const size_t readOutputSize = (partialByteCount && (partialByteCount < maxOutputSize)) ? partialByteCount : maxOutputSize;
const size_t totalBytesToRead = offset + readOutputSize;
// If there is a single extent for this item and the source of the read buffer is going to be
// persistent for the lifetime of the avifDecoder (whether it comes from its own internal
// idatBuffer or from a known-persistent IO), we can avoid buffer duplication and just use the
// preexisting buffer.
avifBool singlePersistentBuffer = ((item->extents.count == 1) && (idatBuffer || io->persistent));
if (!singlePersistentBuffer) {
// Always allocate the item's full size here, as progressive image decodes will do partial
// reads into this buffer and begin feeding the buffer to the underlying AV1 decoder, but
// will then write more into this buffer without flushing the AV1 decoder (which is still
// holding the address of the previous allocation of this buffer). This strategy avoids
// use-after-free issues in the AV1 decoder and unnecessary reallocs as a typical
// progressive decode use case will eventually decode the final layer anyway.
AVIF_CHECKRES(avifRWDataRealloc(&item->mergedExtents, item->size));
item->ownsMergedExtents = AVIF_TRUE;
}
// Set this until we manage to fill the entire mergedExtents buffer
item->partialMergedExtents = AVIF_TRUE;
size_t writeOffset = 0; // Write offset for item->mergedExtents.data
size_t remainingBytes = totalBytesToRead;
for (uint32_t extentIter = 0; extentIter < item->extents.count; ++extentIter) {
avifExtent * extent = &item->extents.extent[extentIter];
size_t bytesToRead = extent->size;
if (bytesToRead > remainingBytes) {
bytesToRead = remainingBytes;
}
avifROData offsetBuffer;
if (idatBuffer) {
if (extent->offset > idatBuffer->size) {
avifDiagnosticsPrintf(diag, "Item ID %u has impossible extent offset in idat buffer", item->id);
return AVIF_RESULT_BMFF_PARSE_FAILED;
}
// Since extent->offset (a uint64_t) is not bigger than idatBuffer->size (a size_t),
// it is safe to cast extent->offset to size_t.
const size_t extentOffset = (size_t)extent->offset;
if (extent->size > idatBuffer->size - extentOffset) {
avifDiagnosticsPrintf(diag, "Item ID %u has impossible extent size in idat buffer", item->id);
return AVIF_RESULT_BMFF_PARSE_FAILED;
}
offsetBuffer.data = idatBuffer->data + extentOffset;
offsetBuffer.size = idatBuffer->size - extentOffset;
} else {
// construction_method: file(0)
if ((io->sizeHint > 0) && (extent->offset > io->sizeHint)) {
avifDiagnosticsPrintf(diag, "Item ID %u extent offset failed size hint sanity check. Truncated data?", item->id);
return AVIF_RESULT_BMFF_PARSE_FAILED;
}
avifResult readResult = io->read(io, 0, extent->offset, bytesToRead, &offsetBuffer);
if (readResult != AVIF_RESULT_OK) {
return readResult;
}
if (bytesToRead != offsetBuffer.size) {
avifDiagnosticsPrintf(diag,
"Item ID %u tried to read %zu bytes, but only received %zu bytes",
item->id,
bytesToRead,
offsetBuffer.size);
return AVIF_RESULT_TRUNCATED_DATA;
}
}
if (singlePersistentBuffer) {
memcpy(&item->mergedExtents, &offsetBuffer, sizeof(avifRWData));
item->mergedExtents.size = bytesToRead;
} else {
AVIF_ASSERT_OR_RETURN(item->ownsMergedExtents);
AVIF_ASSERT_OR_RETURN(writeOffset < item->mergedExtents.size);
AVIF_ASSERT_OR_RETURN(bytesToRead <= item->mergedExtents.size - writeOffset);
memcpy(item->mergedExtents.data + writeOffset, offsetBuffer.data, bytesToRead);
writeOffset += bytesToRead;
}
remainingBytes -= bytesToRead;
if (remainingBytes == 0) {
// This happens when partialByteCount is set
break;
}
}
if (remainingBytes != 0) {
// This should be impossible?
avifDiagnosticsPrintf(diag, "Item ID %u has %zu unexpected trailing bytes", item->id, remainingBytes);
return AVIF_RESULT_TRUNCATED_DATA;
}
outData->data = item->mergedExtents.data + offset;
outData->size = readOutputSize;
item->partialMergedExtents = (item->size != totalBytesToRead);
return AVIF_RESULT_OK;
}
// Returns the avifCodecType of the first tile of the gridItem.
static avifCodecType avifDecoderItemGetGridCodecType(const avifDecoderItem * gridItem)
{
for (uint32_t i = 0; i < gridItem->meta->items.count; ++i) {
avifDecoderItem * item = gridItem->meta->items.item[i];
const avifCodecType tileCodecType = avifGetCodecType(item->type);
if ((item->dimgForID == gridItem->id) && (tileCodecType != AVIF_CODEC_TYPE_UNKNOWN)) {
return tileCodecType;
}
}
return AVIF_CODEC_TYPE_UNKNOWN;
}
// Fills the dimgIdxToItemIdx array with a mapping from each 0-based tile index in the 'dimg' reference
// to its corresponding 0-based index in the avifMeta::items array.
static avifResult avifFillDimgIdxToItemIdxArray(uint32_t * dimgIdxToItemIdx, uint32_t numExpectedTiles, const avifDecoderItem * gridItem)
{
const uint32_t itemIndexNotSet = UINT32_MAX;
for (uint32_t dimgIdx = 0; dimgIdx < numExpectedTiles; ++dimgIdx) {
dimgIdxToItemIdx[dimgIdx] = itemIndexNotSet;
}
uint32_t numTiles = 0;
for (uint32_t i = 0; i < gridItem->meta->items.count; ++i) {
if (gridItem->meta->items.item[i]->dimgForID == gridItem->id) {
const uint32_t tileItemDimgIdx = gridItem->meta->items.item[i]->dimgIdx;
AVIF_CHECKERR(tileItemDimgIdx < numExpectedTiles, AVIF_RESULT_INVALID_IMAGE_GRID);
AVIF_CHECKERR(dimgIdxToItemIdx[tileItemDimgIdx] == itemIndexNotSet, AVIF_RESULT_INVALID_IMAGE_GRID);
dimgIdxToItemIdx[tileItemDimgIdx] = i;
++numTiles;
}
}
// The number of tiles has been verified in avifDecoderItemReadAndParse().
AVIF_ASSERT_OR_RETURN(numTiles == numExpectedTiles);
return AVIF_RESULT_OK;
}
// Copies the codec type property (av1C or av2C) from the first grid tile to the grid item.
// Also checks that all tiles have the same codec type and that it's valid.
static avifResult avifDecoderAdoptGridTileCodecType(avifDecoder * decoder,
avifDecoderItem * gridItem,
const uint32_t * dimgIdxToItemIdx,
uint32_t numTiles)
{
avifDecoderItem * firstTileItem = NULL;
for (uint32_t dimgIdx = 0; dimgIdx < numTiles; ++dimgIdx) {
const uint32_t itemIdx = dimgIdxToItemIdx[dimgIdx];
AVIF_ASSERT_OR_RETURN(itemIdx < gridItem->meta->items.count);
avifDecoderItem * item = gridItem->meta->items.item[itemIdx];
// According to HEIF (ISO 14496-12), Section 6.6.2.3.1, the SingleItemTypeReferenceBox of type 'dimg'
// identifies the input images of the derived image item of type 'grid'. Since the reference_count
// shall be equal to rows*columns, unknown tile item types cannot be skipped but must be considered
// as errors.
const avifCodecType tileCodecType = avifGetCodecType(item->type);
if (tileCodecType == AVIF_CODEC_TYPE_UNKNOWN) {
char type[4];
for (int j = 0; j < 4; j++) {
if (isprint((unsigned char)item->type[j])) {
type[j] = item->type[j];
} else {
type[j] = '.';
}
}
avifDiagnosticsPrintf(&decoder->diag,
"Tile item ID %u has an unknown item type '%.4s' (%02x%02x%02x%02x)",
item->id,
type,
item->type[0],
item->type[1],
item->type[2],
item->type[3]);
return AVIF_RESULT_INVALID_IMAGE_GRID;
}
if (item->hasUnsupportedEssentialProperty) {
// An essential property isn't supported by libavif; can't
// decode a grid image if any tile in the grid isn't supported.
avifDiagnosticsPrintf(&decoder->diag, "Grid image contains tile with an unsupported property marked as essential");
return AVIF_RESULT_INVALID_IMAGE_GRID;
}
if (firstTileItem == NULL) {
firstTileItem = item;
// Adopt the configuration property of the first image item tile, so that it can be queried from
// the top-level color/alpha item during avifDecoderReset().
const avifCodecType codecType = avifGetCodecType(item->type);
const char * configPropName = avifGetConfigurationPropertyName(codecType);
const avifProperty * srcProp = avifPropertyArrayFind(&item->properties, configPropName);
if (!srcProp) {
avifDiagnosticsPrintf(&decoder->diag, "Grid image's first tile is missing an %s property", configPropName);
return AVIF_RESULT_INVALID_IMAGE_GRID;
}
avifProperty * dstProp = (avifProperty *)avifArrayPush(&gridItem->properties);
AVIF_CHECKERR(dstProp != NULL, AVIF_RESULT_OUT_OF_MEMORY);
*dstProp = *srcProp;
} else if (memcmp(item->type, firstTileItem->type, 4)) {
// MIAF (ISO 23000-22:2019), Section 7.3.11.4.1:
// All input images of a grid image item shall use the same coding format [...]
// The coding format is defined by the item type.
avifDiagnosticsPrintf(&decoder->diag,
"Tile item ID %u of type '%.4s' differs from other tile type '%.4s'",
item->id,
(const char *)item->type,
(const char *)firstTileItem->type);
return AVIF_RESULT_INVALID_IMAGE_GRID;
}
}
return AVIF_RESULT_OK;
}
// If the item is a grid, copies the codec type property (av1C or av2C) from the first grid tile to the grid item.
// Also checks that all tiles have the same codec type and that it's valid.
static avifResult avifDecoderAdoptGridTileCodecTypeIfNeeded(avifDecoder * decoder, avifDecoderItem * item, const avifTileInfo * info)
{
if ((info->grid.rows > 0) && (info->grid.columns > 0)) {
// The number of tiles was verified in avifDecoderItemReadAndParse().
const uint32_t numTiles = info->grid.rows * info->grid.columns;
uint32_t * dimgIdxToItemIdx = (uint32_t *)avifAlloc(numTiles * sizeof(uint32_t));
AVIF_CHECKERR(dimgIdxToItemIdx != NULL, AVIF_RESULT_OUT_OF_MEMORY);
avifResult result = avifFillDimgIdxToItemIdxArray(dimgIdxToItemIdx, numTiles, item);
if (result == AVIF_RESULT_OK) {
result = avifDecoderAdoptGridTileCodecType(decoder, item, dimgIdxToItemIdx, numTiles);
}
avifFree(dimgIdxToItemIdx);
AVIF_CHECKRES(result);
}
return AVIF_RESULT_OK;
}
// Creates the tiles and associate them to the items in the order of the 'dimg' association.
static avifResult avifDecoderGenerateImageGridTiles(avifDecoder * decoder,
avifDecoderItem * gridItem,
avifItemCategory itemCategory,
const uint32_t * dimgIdxToItemIdx,
uint32_t numTiles)
{
avifBool progressive = AVIF_TRUE;
for (uint32_t dimgIdx = 0; dimgIdx < numTiles; ++dimgIdx) {
const uint32_t itemIdx = dimgIdxToItemIdx[dimgIdx];
AVIF_ASSERT_OR_RETURN(itemIdx < gridItem->meta->items.count);
avifDecoderItem * item = gridItem->meta->items.item[itemIdx];
const avifCodecType tileCodecType = avifGetCodecType(item->type);
AVIF_CHECKERR(tileCodecType != AVIF_CODEC_TYPE_UNKNOWN, AVIF_RESULT_INVALID_IMAGE_GRID);
const avifTile * tile =
avifDecoderDataCreateTile(decoder->data, tileCodecType, item->width, item->height, avifDecoderItemOperatingPoint(item));
AVIF_CHECKERR(tile != NULL, AVIF_RESULT_OUT_OF_MEMORY);
AVIF_CHECKRES(avifCodecDecodeInputFillFromDecoderItem(tile->input,
item,
decoder->allowProgressive,
decoder->imageCountLimit,
decoder->io->sizeHint,
&decoder->diag));
tile->input->itemCategory = itemCategory;
if (!item->progressive) {
progressive = AVIF_FALSE;
}
}
if (itemCategory == AVIF_ITEM_COLOR && progressive) {
// If all the items that make up the grid are progressive, then propagate that status to the top-level grid item.
gridItem->progressive = AVIF_TRUE;
}
return AVIF_RESULT_OK;
}
// Allocates the dstImage. Also verifies some spec compliance rules for grids, if relevant.
static avifResult avifDecoderDataAllocateImagePlanes(const avifDecoderData * data, const avifTileInfo * info, avifImage * dstImage, avifBool * cicpSet)
{
const avifTile * tile = &data->tiles.tile[info->firstTileIndex];
uint32_t dstWidth;
uint32_t dstHeight;
if (info->grid.rows > 0 && info->grid.columns > 0) {
const avifImageGrid * grid = &info->grid;
// Validate grid image size and tile size.
//
// HEIF (ISO/IEC 23008-12:2017), Section 6.6.2.3.1:
// The tiled input images shall completely "cover" the reconstructed image grid canvas, ...
if ((((uint64_t)tile->image->width * grid->columns) < grid->outputWidth) ||
(((uint64_t)tile->image->height * grid->rows) < grid->outputHeight)) {
avifDiagnosticsPrintf(data->diag,
"Grid image tiles do not completely cover the image (HEIF (ISO/IEC 23008-12:2017), Section 6.6.2.3.1)");
return AVIF_RESULT_INVALID_IMAGE_GRID;
}
// Tiles in the rightmost column and bottommost row must overlap the reconstructed image grid canvas. See MIAF (ISO/IEC 23000-22:2019), Section 7.3.11.4.2, Figure 2.
if ((((uint64_t)tile->image->width * (grid->columns - 1)) >= grid->outputWidth) ||
(((uint64_t)tile->image->height * (grid->rows - 1)) >= grid->outputHeight)) {
avifDiagnosticsPrintf(data->diag,
"Grid image tiles in the rightmost column and bottommost row do not overlap the reconstructed image grid canvas. See MIAF (ISO/IEC 23000-22:2019), Section 7.3.11.4.2, Figure 2");
return AVIF_RESULT_INVALID_IMAGE_GRID;
}
if (!avifAreGridDimensionsValid(tile->image->yuvFormat,
grid->outputWidth,
grid->outputHeight,
tile->image->width,
tile->image->height,
data->diag)) {
return AVIF_RESULT_INVALID_IMAGE_GRID;
}
dstWidth = grid->outputWidth;
dstHeight = grid->outputHeight;
} else {
// Only one tile. Width and height are inherited from the 'ispe' property of the corresponding avifDecoderItem.
dstWidth = tile->width;
dstHeight = tile->height;
}
const avifBool alpha = avifIsAlpha(tile->input->itemCategory);
if (alpha) {
// An alpha tile does not contain any YUV pixels.
AVIF_ASSERT_OR_RETURN(tile->image->yuvFormat == AVIF_PIXEL_FORMAT_NONE);
}
const uint32_t dstDepth = tile->image->depth;
// Lazily populate dstImage with the new frame's properties.
const avifBool dimsOrDepthIsDifferent = (dstImage->width != dstWidth) || (dstImage->height != dstHeight) ||
(dstImage->depth != dstDepth);
const avifBool yuvFormatIsDifferent = !alpha && (dstImage->yuvFormat != tile->image->yuvFormat);
if (dimsOrDepthIsDifferent || yuvFormatIsDifferent) {
if (alpha) {
// Alpha doesn't match size, just bail out
avifDiagnosticsPrintf(data->diag, "Alpha plane dimensions do not match color plane dimensions");
return AVIF_RESULT_INVALID_IMAGE_GRID;
}
if (dimsOrDepthIsDifferent) {
avifImageFreePlanes(dstImage, AVIF_PLANES_ALL);
dstImage->width = dstWidth;
dstImage->height = dstHeight;
dstImage->depth = dstDepth;
}
if (yuvFormatIsDifferent) {
avifImageFreePlanes(dstImage, AVIF_PLANES_YUV);
dstImage->yuvFormat = tile->image->yuvFormat;
}
// Keep dstImage->yuvRange which is already set to its correct value
// (extracted from the 'colr' box if parsed or from a Sequence Header OBU otherwise).
if (!*cicpSet) {
*cicpSet = AVIF_TRUE;
dstImage->colorPrimaries = tile->image->colorPrimaries;
dstImage->transferCharacteristics = tile->image->transferCharacteristics;
dstImage->matrixCoefficients = tile->image->matrixCoefficients;
}
}
if (avifImageAllocatePlanes(dstImage, alpha ? AVIF_PLANES_A : AVIF_PLANES_YUV) != AVIF_RESULT_OK) {
avifDiagnosticsPrintf(data->diag, "Image allocation failure");
return AVIF_RESULT_OUT_OF_MEMORY;
}
return AVIF_RESULT_OK;
}
// Copies over the pixels from the tile into dstImage.
// Verifies that the relevant properties of the tile match those of the first tile in case of a grid.
static avifResult avifDecoderDataCopyTileToImage(avifDecoderData * data,
const avifTileInfo * info,
avifImage * dstImage,
const avifTile * tile,
unsigned int tileIndex)
{
const avifTile * firstTile = &data->tiles.tile[info->firstTileIndex];
if (tile != firstTile) {
// Check for tile consistency. All tiles in a grid image should match the first tile in the properties checked below.
if ((tile->image->width != firstTile->image->width) || (tile->image->height != firstTile->image->height) ||
(tile->image->depth != firstTile->image->depth) || (tile->image->yuvFormat != firstTile->image->yuvFormat) ||
(tile->image->yuvRange != firstTile->image->yuvRange) || (tile->image->colorPrimaries != firstTile->image->colorPrimaries) ||
(tile->image->transferCharacteristics != firstTile->image->transferCharacteristics) ||
(tile->image->matrixCoefficients != firstTile->image->matrixCoefficients)) {
avifDiagnosticsPrintf(data->diag, "Grid image contains mismatched tiles");
return AVIF_RESULT_INVALID_IMAGE_GRID;
}
}
// Only keep the relevant planes in the destination image. Otherwise,
// unjustified failures may come from trying to copy alpha tiles with odd
// coordinates into the dstImage when the chroma planes are subsampled.
avifImage dstView;
avifImageSetDefaults(&dstView);
const avifCropRect srcViewRect = { 0, 0, dstImage->width, dstImage->height };
AVIF_ASSERT_OR_RETURN(avifImageSetViewRect(&dstView, dstImage, &srcViewRect) == AVIF_RESULT_OK);
if (avifIsAlpha(tile->input->itemCategory)) {
avifImageFreePlanes(&dstView, AVIF_PLANES_YUV);
dstView.yuvFormat = AVIF_PIXEL_FORMAT_NONE;
} else {
avifImageFreePlanes(&dstView, AVIF_PLANES_A);
}
avifImage srcTileView;
avifImageSetDefaults(&srcTileView);
avifImage dstTileView;
avifImageSetDefaults(&dstTileView);
avifCropRect dstTileViewRect = { 0, 0, firstTile->image->width, firstTile->image->height };
if (info->grid.rows > 0 && info->grid.columns > 0) {
unsigned int rowIndex = tileIndex / info->grid.columns;
unsigned int colIndex = tileIndex % info->grid.columns;
dstTileViewRect.x = firstTile->image->width * colIndex;
dstTileViewRect.y = firstTile->image->height * rowIndex;
if (dstTileViewRect.x + dstTileViewRect.width > info->grid.outputWidth) {
dstTileViewRect.width = info->grid.outputWidth - dstTileViewRect.x;
}
if (dstTileViewRect.y + dstTileViewRect.height > info->grid.outputHeight) {
dstTileViewRect.height = info->grid.outputHeight - dstTileViewRect.y;
}
}
const avifCropRect srcTileViewRect = { 0, 0, dstTileViewRect.width, dstTileViewRect.height };
AVIF_ASSERT_OR_RETURN(avifImageSetViewRect(&dstTileView, &dstView, &dstTileViewRect) == AVIF_RESULT_OK);
AVIF_ASSERT_OR_RETURN(avifImageSetViewRect(&srcTileView, tile->image, &srcTileViewRect) == AVIF_RESULT_OK);
avifImageCopySamples(&dstTileView, &srcTileView, avifIsAlpha(tile->input->itemCategory) ? AVIF_PLANES_A : AVIF_PLANES_YUV);
return AVIF_RESULT_OK;
}
// If colorId == 0 (a sentinel value as item IDs must be nonzero), accept any found EXIF/XMP metadata. Passing in 0
// is used when finding metadata in a meta box embedded in a trak box, as any items inside of a meta box that is
// inside of a trak box are implicitly associated to the track.
static avifResult avifDecoderFindMetadata(avifDecoder * decoder, avifMeta * meta, avifImage * image, uint32_t colorId)
{
if (decoder->ignoreExif && decoder->ignoreXMP) {
// Nothing to do!
return AVIF_RESULT_OK;
}
for (uint32_t itemIndex = 0; itemIndex < meta->items.count; ++itemIndex) {
avifDecoderItem * item = meta->items.item[itemIndex];
if (!item->size) {
continue;
}
if (item->hasUnsupportedEssentialProperty) {
// An essential property isn't supported by libavif; ignore the item.
continue;
}
if ((colorId > 0) && (item->descForID != colorId)) {
// Not a content description (metadata) for the colorOBU, skip it
continue;
}
if (!decoder->ignoreExif && !memcmp(item->type, "Exif", 4)) {
avifROData exifContents;
avifResult readResult = avifDecoderItemRead(item, decoder->io, &exifContents, 0, 0, &decoder->diag);
if (readResult != AVIF_RESULT_OK) {
return readResult;
}
// Advance past Annex A.2.1's header
BEGIN_STREAM(exifBoxStream, exifContents.data, exifContents.size, &decoder->diag, "Exif header");
#if defined(AVIF_ENABLE_EXPERIMENTAL_MINI)
// The MinimizedImageBox does not signal the exifTiffHeaderOffset.
if (!meta->fromMiniBox)
#endif
{
uint32_t exifTiffHeaderOffset;
AVIF_CHECKERR(avifROStreamReadU32(&exifBoxStream, &exifTiffHeaderOffset),
AVIF_RESULT_INVALID_EXIF_PAYLOAD); // unsigned int(32) exif_tiff_header_offset;
size_t expectedExifTiffHeaderOffset;
AVIF_CHECKRES(avifGetExifTiffHeaderOffset(avifROStreamCurrent(&exifBoxStream),
avifROStreamRemainingBytes(&exifBoxStream),
&expectedExifTiffHeaderOffset));
AVIF_CHECKERR(exifTiffHeaderOffset == expectedExifTiffHeaderOffset, AVIF_RESULT_INVALID_EXIF_PAYLOAD);
}
AVIF_CHECKRES(avifRWDataSet(&image->exif, avifROStreamCurrent(&exifBoxStream), avifROStreamRemainingBytes(&exifBoxStream)));
} else if (!decoder->ignoreXMP && !memcmp(item->type, "mime", 4) &&
!strcmp(item->contentType.contentType, AVIF_CONTENT_TYPE_XMP)) {
avifROData xmpContents;
avifResult readResult = avifDecoderItemRead(item, decoder->io, &xmpContents, 0, 0, &decoder->diag);
if (readResult != AVIF_RESULT_OK) {
return readResult;
}
AVIF_CHECKRES(avifImageSetMetadataXMP(image, xmpContents.data, xmpContents.size));
}
}
return AVIF_RESULT_OK;
}
// ---------------------------------------------------------------------------
// URN
static avifBool isAlphaURN(const char * urn)
{
return !strcmp(urn, AVIF_URN_ALPHA0) || !strcmp(urn, AVIF_URN_ALPHA1);
}
// ---------------------------------------------------------------------------
// BMFF Parsing
static avifBool avifParseHandlerBox(const uint8_t * raw, size_t rawLen, uint8_t handlerType[4], avifDiagnostics * diag)
{
BEGIN_STREAM(s, raw, rawLen, diag, "Box[hdlr]");
AVIF_CHECK(avifROStreamReadAndEnforceVersion(&s, /*enforcedVersion=*/0, /*flags=*/NULL));
uint32_t predefined;
AVIF_CHECK(avifROStreamReadU32(&s, &predefined)); // unsigned int(32) pre_defined = 0;
if (predefined != 0) {
avifDiagnosticsPrintf(diag, "Box[hdlr] contains a pre_defined value that is nonzero");
return AVIF_FALSE;
}
AVIF_CHECK(avifROStreamRead(&s, handlerType, 4)); // unsigned int(32) handler_type;
for (int i = 0; i < 3; ++i) {
uint32_t reserved;
AVIF_CHECK(avifROStreamReadU32(&s, &reserved)); // const unsigned int(32)[3] reserved = 0;
}
// Verify that a valid string is here, but don't bother to store it
AVIF_CHECK(avifROStreamReadString(&s, NULL, 0)); // string name;
return AVIF_TRUE;
}
static avifResult avifParseItemLocationBox(avifMeta * meta, const uint8_t * raw, size_t rawLen, avifDiagnostics * diag)
{
BEGIN_STREAM(s, raw, rawLen, diag, "Box[iloc]");
// Section 8.11.3.2 of ISO/IEC 14496-12.
uint8_t version;
AVIF_CHECKERR(avifROStreamReadVersionAndFlags(&s, &version, NULL), AVIF_RESULT_BMFF_PARSE_FAILED);
if (version > 2) {
avifDiagnosticsPrintf(diag, "Box[iloc] has an unsupported version [%u]", version);
return AVIF_RESULT_BMFF_PARSE_FAILED;
}
uint8_t offsetSize, lengthSize, baseOffsetSize, indexSize = 0;
uint32_t reserved;
AVIF_CHECKERR(avifROStreamReadBitsU8(&s, &offsetSize, /*bitCount=*/4), AVIF_RESULT_BMFF_PARSE_FAILED); // unsigned int(4) offset_size;
AVIF_CHECKERR(avifROStreamReadBitsU8(&s, &lengthSize, /*bitCount=*/4), AVIF_RESULT_BMFF_PARSE_FAILED); // unsigned int(4) length_size;
AVIF_CHECKERR(avifROStreamReadBitsU8(&s, &baseOffsetSize, /*bitCount=*/4), AVIF_RESULT_BMFF_PARSE_FAILED); // unsigned int(4) base_offset_size;
if (version == 1 || version == 2) {
AVIF_CHECKERR(avifROStreamReadBitsU8(&s, &indexSize, /*bitCount=*/4), AVIF_RESULT_BMFF_PARSE_FAILED); // unsigned int(4) index_size;
} else {
AVIF_CHECKERR(avifROStreamReadBitsU32(&s, &reserved, /*bitCount=*/4), AVIF_RESULT_BMFF_PARSE_FAILED); // unsigned int(4) reserved;
}
// Section 8.11.3.3 of ISO/IEC 14496-12.
if ((offsetSize != 0 && offsetSize != 4 && offsetSize != 8) || (lengthSize != 0 && lengthSize != 4 && lengthSize != 8) ||
(baseOffsetSize != 0 && baseOffsetSize != 4 && baseOffsetSize != 8) || (indexSize != 0 && indexSize != 4 && indexSize != 8)) {
avifDiagnosticsPrintf(diag, "Box[iloc] has an invalid size");
return AVIF_RESULT_BMFF_PARSE_FAILED;
}
uint16_t tmp16;
uint32_t itemCount;
if (version < 2) {
AVIF_CHECKERR(avifROStreamReadU16(&s, &tmp16), AVIF_RESULT_BMFF_PARSE_FAILED); // unsigned int(16) item_count;
itemCount = tmp16;
} else {
AVIF_CHECKERR(avifROStreamReadU32(&s, &itemCount), AVIF_RESULT_BMFF_PARSE_FAILED); // unsigned int(32) item_count;
}
for (uint32_t i = 0; i < itemCount; ++i) {
uint32_t itemID;
if (version < 2) {
AVIF_CHECKERR(avifROStreamReadU16(&s, &tmp16), AVIF_RESULT_BMFF_PARSE_FAILED); // unsigned int(16) item_ID;
itemID = tmp16;
} else {
AVIF_CHECKERR(avifROStreamReadU32(&s, &itemID), AVIF_RESULT_BMFF_PARSE_FAILED); // unsigned int(32) item_ID;
}
AVIF_CHECKRES(avifCheckItemID("iloc", itemID, diag));
avifDecoderItem * item;
AVIF_CHECKRES(avifMetaFindOrCreateItem(meta, itemID, &item));
if (item->extents.count > 0) {
// This item has already been given extents via this iloc box. This is invalid.
avifDiagnosticsPrintf(diag, "Item ID [%u] contains duplicate sets of extents", itemID);
return AVIF_RESULT_BMFF_PARSE_FAILED;
}
if (version == 1 || version == 2) {
AVIF_CHECKERR(avifROStreamReadBitsU32(&s, &reserved, /*bitCount=*/12), AVIF_RESULT_BMFF_PARSE_FAILED); // unsigned int(12) reserved = 0;
if (reserved) {
avifDiagnosticsPrintf(diag, "Box[iloc] has a non null reserved field [%u]", reserved);
return AVIF_RESULT_BMFF_PARSE_FAILED;
}
uint8_t constructionMethod;
AVIF_CHECKERR(avifROStreamReadBitsU8(&s, &constructionMethod, /*bitCount=*/4),
AVIF_RESULT_BMFF_PARSE_FAILED); // unsigned int(4) construction_method;
if (constructionMethod != 0 /* file offset */ && constructionMethod != 1 /* idat offset */) {
// construction method 2 (item offset) unsupported
avifDiagnosticsPrintf(diag, "Box[iloc] has an unsupported construction method [%u]", constructionMethod);
return AVIF_RESULT_BMFF_PARSE_FAILED;
}
if (constructionMethod == 1) {
item->idatStored = AVIF_TRUE;
}
}
uint16_t dataReferenceIndex;
AVIF_CHECKERR(avifROStreamReadU16(&s, &dataReferenceIndex), AVIF_RESULT_BMFF_PARSE_FAILED); // unsigned int(16) data_reference_index;
uint64_t baseOffset;
AVIF_CHECKERR(avifROStreamReadUX8(&s, &baseOffset, baseOffsetSize), AVIF_RESULT_BMFF_PARSE_FAILED); // unsigned int(base_offset_size*8) base_offset;
uint16_t extentCount;
AVIF_CHECKERR(avifROStreamReadU16(&s, &extentCount), AVIF_RESULT_BMFF_PARSE_FAILED); // unsigned int(16) extent_count;
for (int extentIter = 0; extentIter < extentCount; ++extentIter) {
if ((version == 1 || version == 2) && indexSize > 0) {
// Section 8.11.3.1 of ISO/IEC 14496-12:
// The item_reference_index is only used for the method item_offset; it indicates the 1-based index
// of the item reference with referenceType 'iloc' linked from this item. If index_size is 0, then
// the value 1 is implied; the value 0 is reserved.
uint64_t itemReferenceIndex; // Ignored unless construction_method=2 which is unsupported, but still read it.
AVIF_CHECKERR(avifROStreamReadUX8(&s, &itemReferenceIndex, indexSize),
AVIF_RESULT_BMFF_PARSE_FAILED); // unsigned int(index_size*8) item_reference_index;
}
uint64_t extentOffset;
AVIF_CHECKERR(avifROStreamReadUX8(&s, &extentOffset, offsetSize), AVIF_RESULT_BMFF_PARSE_FAILED); // unsigned int(offset_size*8) extent_offset;
uint64_t extentLength;
AVIF_CHECKERR(avifROStreamReadUX8(&s, &extentLength, lengthSize), AVIF_RESULT_BMFF_PARSE_FAILED); // unsigned int(length_size*8) extent_length;
avifExtent * extent = (avifExtent *)avifArrayPush(&item->extents);
AVIF_CHECKERR(extent != NULL, AVIF_RESULT_OUT_OF_MEMORY);
if (extentOffset > UINT64_MAX - baseOffset) {
avifDiagnosticsPrintf(diag,
"Item ID [%u] contains an extent offset which overflows: [base: %" PRIu64 " offset:%" PRIu64 "]",
itemID,
baseOffset,
extentOffset);
return AVIF_RESULT_BMFF_PARSE_FAILED;
}
uint64_t offset = baseOffset + extentOffset;
extent->offset = offset;
#if UINT64_MAX > SIZE_MAX
if (extentLength > SIZE_MAX) {
avifDiagnosticsPrintf(diag, "Item ID [%u] contains an extent length which overflows: [%" PRIu64 "]", itemID, extentLength);
return AVIF_RESULT_BMFF_PARSE_FAILED;
}
#endif
extent->size = (size_t)extentLength;
if (extent->size > SIZE_MAX - item->size) {
avifDiagnosticsPrintf(diag,
"Item ID [%u] contains an extent length which overflows the item size: [%zu, %zu]",
itemID,
extent->size,
item->size);
return AVIF_RESULT_BMFF_PARSE_FAILED;
}
item->size += extent->size;
}
}
return AVIF_RESULT_OK;
}
static avifResult avifParseImageGridBox(avifImageGrid * grid,
const uint8_t * raw,
size_t rawLen,
uint32_t imageSizeLimit,
uint32_t imageDimensionLimit,
avifDiagnostics * diag)
{
BEGIN_STREAM(s, raw, rawLen, diag, "Box[grid]");
uint8_t version, flags;
AVIF_CHECKERR(avifROStreamRead(&s, &version, 1), AVIF_RESULT_BMFF_PARSE_FAILED); // unsigned int(8) version = 0;
if (version != 0) {
avifDiagnosticsPrintf(diag, "Box[grid] has unsupported version [%u]", version);
return AVIF_RESULT_NOT_IMPLEMENTED;
}
uint8_t rowsMinusOne, columnsMinusOne;
AVIF_CHECKERR(avifROStreamRead(&s, &flags, 1), AVIF_RESULT_BMFF_PARSE_FAILED); // unsigned int(8) flags;
AVIF_CHECKERR(avifROStreamRead(&s, &rowsMinusOne, 1), AVIF_RESULT_BMFF_PARSE_FAILED); // unsigned int(8) rows_minus_one;
AVIF_CHECKERR(avifROStreamRead(&s, &columnsMinusOne, 1), AVIF_RESULT_BMFF_PARSE_FAILED); // unsigned int(8) columns_minus_one;
grid->rows = (uint32_t)rowsMinusOne + 1;
grid->columns = (uint32_t)columnsMinusOne + 1;
uint32_t fieldLength = ((flags & 1) + 1) * 16;
if (fieldLength == 16) {
uint16_t outputWidth16, outputHeight16;
AVIF_CHECKERR(avifROStreamReadU16(&s, &outputWidth16), AVIF_RESULT_BMFF_PARSE_FAILED); // unsigned int(FieldLength) output_width;
AVIF_CHECKERR(avifROStreamReadU16(&s, &outputHeight16), AVIF_RESULT_BMFF_PARSE_FAILED); // unsigned int(FieldLength) output_height;
grid->outputWidth = outputWidth16;
grid->outputHeight = outputHeight16;
} else {
if (fieldLength != 32) {
// This should be impossible
avifDiagnosticsPrintf(diag, "Grid box contains illegal field length: [%u]", fieldLength);
return AVIF_RESULT_INVALID_IMAGE_GRID;
}
AVIF_CHECKERR(avifROStreamReadU32(&s, &grid->outputWidth), AVIF_RESULT_BMFF_PARSE_FAILED); // unsigned int(FieldLength) output_width;
AVIF_CHECKERR(avifROStreamReadU32(&s, &grid->outputHeight), AVIF_RESULT_BMFF_PARSE_FAILED); // unsigned int(FieldLength) output_height;
}
if ((grid->outputWidth == 0) || (grid->outputHeight == 0)) {
avifDiagnosticsPrintf(diag, "Grid box contains illegal dimensions: [%u x %u]", grid->outputWidth, grid->outputHeight);
return AVIF_RESULT_INVALID_IMAGE_GRID;
}
if (avifDimensionsTooLarge(grid->outputWidth, grid->outputHeight, imageSizeLimit, imageDimensionLimit)) {
avifDiagnosticsPrintf(diag, "Grid box dimensions are too large: [%u x %u]", grid->outputWidth, grid->outputHeight);
return AVIF_RESULT_NOT_IMPLEMENTED;
}
if (avifROStreamRemainingBytes(&s) != 0) {
return AVIF_RESULT_BMFF_PARSE_FAILED;
}
return AVIF_RESULT_OK;
}
static avifBool avifParseGainMapMetadata(avifGainMap * gainMap, avifROStream * s)
{
uint32_t isMultichannel;
AVIF_CHECK(avifROStreamReadBitsU32(s, &isMultichannel, 1)); // unsigned int(1) is_multichannel;
const uint8_t channelCount = isMultichannel ? 3 : 1;
uint32_t useBaseColorSpace;
AVIF_CHECK(avifROStreamReadBitsU32(s, &useBaseColorSpace, 1)); // unsigned int(1) use_base_colour_space;
gainMap->useBaseColorSpace = useBaseColorSpace ? AVIF_TRUE : AVIF_FALSE;
uint32_t reserved;
AVIF_CHECK(avifROStreamReadBitsU32(s, &reserved, 6)); // unsigned int(6) reserved;
AVIF_CHECK(avifROStreamReadU32(s, &gainMap->baseHdrHeadroom.n)); // unsigned int(32) base_hdr_headroom_numerator;
AVIF_CHECK(avifROStreamReadU32(s, &gainMap->baseHdrHeadroom.d)); // unsigned int(32) base_hdr_headroom_denominator;
AVIF_CHECK(avifROStreamReadU32(s, &gainMap->alternateHdrHeadroom.n)); // unsigned int(32) alternate_hdr_headroom_numerator;
AVIF_CHECK(avifROStreamReadU32(s, &gainMap->alternateHdrHeadroom.d)); // unsigned int(32) alternate_hdr_headroom_denominator;
for (int c = 0; c < channelCount; ++c) {
AVIF_CHECK(avifROStreamReadU32(s, (uint32_t *)&gainMap->gainMapMin[c].n)); // int(32) gain_map_min_numerator;
AVIF_CHECK(avifROStreamReadU32(s, &gainMap->gainMapMin[c].d)); // unsigned int(32) gain_map_min_denominator;
AVIF_CHECK(avifROStreamReadU32(s, (uint32_t *)&gainMap->gainMapMax[c].n)); // int(32) gain_map_max_numerator;
AVIF_CHECK(avifROStreamReadU32(s, &gainMap->gainMapMax[c].d)); // unsigned int(32) gain_map_max_denominator;
AVIF_CHECK(avifROStreamReadU32(s, &gainMap->gainMapGamma[c].n)); // unsigned int(32) gamma_numerator;
AVIF_CHECK(avifROStreamReadU32(s, &gainMap->gainMapGamma[c].d)); // unsigned int(32) gamma_denominator;
AVIF_CHECK(avifROStreamReadU32(s, (uint32_t *)&gainMap->baseOffset[c].n)); // int(32) base_offset_numerator;
AVIF_CHECK(avifROStreamReadU32(s, &gainMap->baseOffset[c].d)); // unsigned int(32) base_offset_denominator;
AVIF_CHECK(avifROStreamReadU32(s, (uint32_t *)&gainMap->alternateOffset[c].n)); // int(32) alternate_offset_numerator;
AVIF_CHECK(avifROStreamReadU32(s, &gainMap->alternateOffset[c].d)); // unsigned int(32) alternate_offset_denominator;
}
// Fill the remaining values by copying those from the first channel.
for (int c = channelCount; c < 3; ++c) {
gainMap->gainMapMin[c] = gainMap->gainMapMin[0];
gainMap->gainMapMax[c] = gainMap->gainMapMax[0];
gainMap->gainMapGamma[c] = gainMap->gainMapGamma[0];
gainMap->baseOffset[c] = gainMap->baseOffset[0];
gainMap->alternateOffset[c] = gainMap->alternateOffset[0];
}
return AVIF_TRUE;
}
// If the gain map's version or minimum_version tag is not supported, returns AVIF_RESULT_NOT_IMPLEMENTED.
static avifResult avifParseToneMappedImageBox(avifGainMap * gainMap, const uint8_t * raw, size_t rawLen, avifDiagnostics * diag)
{
BEGIN_STREAM(s, raw, rawLen, diag, "Box[tmap]");
uint8_t version;
AVIF_CHECKERR(avifROStreamRead(&s, &version, 1), AVIF_RESULT_INVALID_TONE_MAPPED_IMAGE); // unsigned int(8) version = 0;
if (version != 0) {
avifDiagnosticsPrintf(diag, "Box[tmap] has unsupported version [%u]", version);
return AVIF_RESULT_NOT_IMPLEMENTED;
}
uint16_t minimumVersion;
AVIF_CHECKERR(avifROStreamReadU16(&s, &minimumVersion), AVIF_RESULT_INVALID_TONE_MAPPED_IMAGE); // unsigned int(16) minimum_version;
const uint16_t supportedMetadataVersion = 0;
if (minimumVersion > supportedMetadataVersion) {
avifDiagnosticsPrintf(diag, "Box[tmap] has unsupported minimum version [%u]", minimumVersion);
return AVIF_RESULT_NOT_IMPLEMENTED;
}
uint16_t writerVersion;
AVIF_CHECKERR(avifROStreamReadU16(&s, &writerVersion), AVIF_RESULT_INVALID_TONE_MAPPED_IMAGE); // unsigned int(16) writer_version;
AVIF_CHECKERR(writerVersion >= minimumVersion, AVIF_RESULT_INVALID_TONE_MAPPED_IMAGE);
AVIF_CHECKERR(avifParseGainMapMetadata(gainMap, &s), AVIF_RESULT_INVALID_TONE_MAPPED_IMAGE);
if (writerVersion <= supportedMetadataVersion) {
AVIF_CHECKERR(avifROStreamRemainingBytes(&s) == 0, AVIF_RESULT_INVALID_TONE_MAPPED_IMAGE);
}
if (avifGainMapValidateMetadata(gainMap, diag) != AVIF_RESULT_OK) {
return AVIF_RESULT_INVALID_TONE_MAPPED_IMAGE;
}
return AVIF_RESULT_OK;
}
// bit_depth is assumed to be 2 (32-bit).
static avifResult avifParseSampleTransformTokens(avifROStream * s, avifSampleTransformExpression * expression)
{
uint8_t tokenCount;
AVIF_CHECKERR(avifROStreamRead(s, &tokenCount, /*size=*/1), AVIF_RESULT_BMFF_PARSE_FAILED); // unsigned int(8) token_count;
AVIF_CHECKERR(tokenCount != 0, AVIF_RESULT_BMFF_PARSE_FAILED);
AVIF_CHECKERR(avifArrayCreate(expression, sizeof(expression->tokens[0]), tokenCount), AVIF_RESULT_OUT_OF_MEMORY);
for (uint32_t t = 0; t < tokenCount; ++t) {
avifSampleTransformToken * token = (avifSampleTransformToken *)avifArrayPush(expression);
AVIF_CHECKERR(token != NULL, AVIF_RESULT_OUT_OF_MEMORY);
uint8_t tokenValue;
AVIF_CHECKERR(avifROStreamRead(s, &tokenValue, /*size=*/1), AVIF_RESULT_BMFF_PARSE_FAILED); // unsigned int(8) token;
if (tokenValue == AVIF_SAMPLE_TRANSFORM_CONSTANT) {
token->type = AVIF_SAMPLE_TRANSFORM_CONSTANT;
// Two's complement representation is assumed here.
uint32_t constant;
AVIF_CHECKERR(avifROStreamReadU32(s, &constant), AVIF_RESULT_BMFF_PARSE_FAILED); // signed int(1<<(bit_depth+3)) constant;
token->constant = (int32_t)constant;
} else if (tokenValue <= AVIF_SAMPLE_TRANSFORM_LAST_INPUT_IMAGE_ITEM_INDEX) {
AVIF_ASSERT_OR_RETURN(tokenValue >= AVIF_SAMPLE_TRANSFORM_FIRST_INPUT_IMAGE_ITEM_INDEX);
token->type = AVIF_SAMPLE_TRANSFORM_INPUT_IMAGE_ITEM_INDEX;
token->inputImageItemIndex = tokenValue;
} else if (tokenValue >= AVIF_SAMPLE_TRANSFORM_FIRST_UNARY_OPERATOR && tokenValue <= AVIF_SAMPLE_TRANSFORM_LAST_UNARY_OPERATOR) {
token->type = (avifSampleTransformTokenType)tokenValue; // unary operator
} else if (tokenValue >= AVIF_SAMPLE_TRANSFORM_FIRST_BINARY_OPERATOR && tokenValue <= AVIF_SAMPLE_TRANSFORM_LAST_BINARY_OPERATOR) {
token->type = (avifSampleTransformTokenType)tokenValue; // binary operator
} else {
token->type = AVIF_SAMPLE_TRANSFORM_RESERVED;
}
}
AVIF_CHECKERR(avifROStreamRemainingBytes(s) == 0, AVIF_RESULT_BMFF_PARSE_FAILED);
return AVIF_RESULT_OK;
}
// Parses the raw bitstream of the 'sato' Sample Transform derived image item and extracts the expression.
static avifResult avifParseSampleTransformImageBox(const uint8_t * raw,
size_t rawLen,
uint32_t numInputImageItems,
avifSampleTransformExpression * expression,
avifDiagnostics * diag)
{
BEGIN_STREAM(s, raw, rawLen, diag, "Box[sato]");
uint8_t version, reserved, bitDepth;
AVIF_CHECKERR(avifROStreamReadBitsU8(&s, &version, /*bitCount=*/2), AVIF_RESULT_BMFF_PARSE_FAILED); // unsigned int(2) version = 0;
AVIF_CHECKERR(avifROStreamReadBitsU8(&s, &reserved, /*bitCount=*/4), AVIF_RESULT_BMFF_PARSE_FAILED); // unsigned int(4) reserved;
AVIF_CHECKERR(avifROStreamReadBitsU8(&s, &bitDepth, /*bitCount=*/2), AVIF_RESULT_BMFF_PARSE_FAILED); // unsigned int(2) bit_depth;
AVIF_CHECKERR(version == 0, AVIF_RESULT_NOT_IMPLEMENTED);
AVIF_CHECKERR(bitDepth == AVIF_SAMPLE_TRANSFORM_BIT_DEPTH_32, AVIF_RESULT_NOT_IMPLEMENTED);
const avifResult result = avifParseSampleTransformTokens(&s, expression);
if (result != AVIF_RESULT_OK) {
avifArrayDestroy(expression);
return result;
}
if (!avifSampleTransformExpressionIsValid(expression, numInputImageItems)) {
avifArrayDestroy(expression);
return AVIF_RESULT_BMFF_PARSE_FAILED;
}
return AVIF_RESULT_OK;
}
static const avifProperty * avifDecoderItemCodecConfigOrFirstCellCodecConfig(const avifDecoderItem * item)
{
if (!memcmp(item->type, "grid", 4)) {
// In case of a grid, return the codec configuration property of the first cell.
// avifDecoderAdoptGridTileCodecType() copies that property from the first cell to the grid item anyway.
for (uint32_t i = 0; i < item->meta->items.count; ++i) {
avifDecoderItem * inputImageItem = item->meta->items.item[i];
if (inputImageItem->dimgForID == item->id) {
return avifPropertyArrayFind(&inputImageItem->properties,
avifGetConfigurationPropertyName(avifGetCodecType(inputImageItem->type)));
}
}
// The number of tiles was verified in avifDecoderItemReadAndParse().
assert(AVIF_FALSE);
}
return avifPropertyArrayFind(&item->properties, avifGetConfigurationPropertyName(avifGetCodecType(item->type)));
}
static avifResult avifDecoderSampleTransformItemValidateProperties(const avifDecoderItem * satoItem, avifDiagnostics * diag)
{
AVIF_ASSERT_OR_RETURN(memcmp(satoItem->type, "sato", 4) == 0);
const avifProperty * pixiProp = avifPropertyArrayFind(&satoItem->properties, "pixi");
if (!pixiProp) {
avifDiagnosticsPrintf(diag, "Item ID %u of type 'sato' is missing mandatory pixi property", satoItem->id);
return AVIF_RESULT_BMFF_PARSE_FAILED;
}
for (uint8_t i = 1; i < pixiProp->u.pixi.planeCount; ++i) {
// This is enforced in avifParsePixelInformationProperty().
AVIF_ASSERT_OR_RETURN(pixiProp->u.pixi.planeDepths[i] == pixiProp->u.pixi.planeDepths[0]);
}
AVIF_ASSERT_OR_RETURN(pixiProp->u.pixi.planeCount >= 1);
const uint8_t depth = pixiProp->u.pixi.planeDepths[0];
if (depth != 8 && depth != 10 && depth != 12 && depth != 16) {
avifDiagnosticsPrintf(diag,
"Item ID %u of type 'sato' with depth %u (specified by pixi property) is not supported",
satoItem->id,
depth);
return AVIF_RESULT_NOT_IMPLEMENTED;
}
const avifProperty * ispeProp = avifPropertyArrayFind(&satoItem->properties, "ispe");
if (!ispeProp) {
avifDiagnosticsPrintf(diag, "Item ID %u of type 'sato' is missing mandatory ispe property", satoItem->id);
return AVIF_RESULT_BMFF_PARSE_FAILED;
}
// Check that all input image items of the 'sato' derived image item share the same properties.
for (uint32_t i = 0; i < satoItem->meta->items.count; ++i) {
avifDecoderItem * inputImageItem = satoItem->meta->items.item[i];
if (inputImageItem->dimgForID != satoItem->id) {
continue;
}
// Require all input image items of the 'sato' derived image item to be associated with a ImageSpatialExtentsProperty.
const avifProperty * inputImageItemIspeProp = avifPropertyArrayFind(&inputImageItem->properties, "ispe");
if (inputImageItemIspeProp == NULL) {
avifDiagnosticsPrintf(diag, "Item ID %u is missing mandatory ispe property", inputImageItem->id);
return AVIF_RESULT_BMFF_PARSE_FAILED;
}
// The codec configuration property must be present, at least on the first cell for a 'grid' item.
const avifProperty * inputImageItemCodecConfig = avifDecoderItemCodecConfigOrFirstCellCodecConfig(inputImageItem);
if (inputImageItemCodecConfig == NULL) {
avifDiagnosticsPrintf(diag,
"Item ID %u of type '%.4s' is missing mandatory codec configuration property",
inputImageItem->id,
(const char *)inputImageItem->type);
return AVIF_RESULT_BMFF_PARSE_FAILED;
}
for (uint32_t j = i + 1; j < satoItem->meta->items.count; ++j) {
avifDecoderItem * otherInputImageItem = satoItem->meta->items.item[j];
if (otherInputImageItem->dimgForID != satoItem->id) {
continue;
}
// Require all input image items of the 'sato' derived image item to be associated with a ImageSpatialExtentsProperty.
const avifProperty * otherInputImageItemIspeProp = avifPropertyArrayFind(&otherInputImageItem->properties, "ispe");
if (otherInputImageItemIspeProp == NULL) {
avifDiagnosticsPrintf(diag,
"Item ID %u of type '%.4s' is missing mandatory ispe property",
otherInputImageItem->id,
(const char *)otherInputImageItem->type);
return AVIF_RESULT_BMFF_PARSE_FAILED;
}
if (inputImageItemIspeProp->u.ispe.width != otherInputImageItemIspeProp->u.ispe.width ||
inputImageItemIspeProp->u.ispe.height != otherInputImageItemIspeProp->u.ispe.height) {
avifDiagnosticsPrintf(diag,
"The fields of the ispe property of item ID %u of type '%.4s' differs from item ID %u",
inputImageItem->id,
(const char *)inputImageItem->type,
otherInputImageItem->id);
return AVIF_RESULT_BMFF_PARSE_FAILED;
}
// The codec configuration property must be present, at least on the first cell for a 'grid' item.
const avifProperty * otherInputImageItemCodecConfig = avifDecoderItemCodecConfigOrFirstCellCodecConfig(otherInputImageItem);
if (otherInputImageItemCodecConfig == NULL) {
avifDiagnosticsPrintf(diag,
"Item ID %u of type '%.4s' is missing mandatory codec configuration property",
otherInputImageItem->id,
(const char *)otherInputImageItem->type);
return AVIF_RESULT_BMFF_PARSE_FAILED;
}
if (inputImageItemCodecConfig->u.av1C.monochrome != otherInputImageItemCodecConfig->u.av1C.monochrome ||
inputImageItemCodecConfig->u.av1C.chromaSubsamplingX != otherInputImageItemCodecConfig->u.av1C.chromaSubsamplingX ||
inputImageItemCodecConfig->u.av1C.chromaSubsamplingY != otherInputImageItemCodecConfig->u.av1C.chromaSubsamplingY ||
inputImageItemCodecConfig->u.av1C.chromaSamplePosition != otherInputImageItemCodecConfig->u.av1C.chromaSamplePosition) {
avifDiagnosticsPrintf(diag,
"The plane count or subsampling in the codec configuration property of item ID %u of type '%.4s' differs from item ID %u",
inputImageItem->id,
(const char *)inputImageItem->type,
otherInputImageItem->id);
return AVIF_RESULT_BMFF_PARSE_FAILED;
}
// If the input image item of the 'sato' derived image item is itself a grid,
// its own input image items will be checked in avifDecoderItemValidateProperties().
}
break;
}
AVIF_CHECKERR(avifPropertyArrayFind(&satoItem->properties, "clap") == NULL, AVIF_RESULT_NOT_IMPLEMENTED);
return AVIF_RESULT_OK;
}
// Extracts the codecType from the item type or from its children.
// Also parses and outputs grid information if the item is a grid.
// isItemInInput must be false if the item is a made-up structure
// (and thus not part of the parseable input bitstream).
static avifResult avifDecoderItemReadAndParse(const avifDecoder * decoder,
avifDecoderItem * item,
avifBool isItemInInput,
avifImageGrid * grid,
avifCodecType * codecType)
{
if (!memcmp(item->type, "grid", 4)) {
if (isItemInInput) {
avifROData readData;
AVIF_CHECKRES(avifDecoderItemRead(item, decoder->io, &readData, 0, 0, decoder->data->diag));
AVIF_CHECKRES(avifParseImageGridBox(grid,
readData.data,
readData.size,
decoder->imageSizeLimit,
decoder->imageDimensionLimit,
decoder->data->diag));
// Validate that there are exactly the same number of dimg items to form the grid.
uint32_t dimgItemCount = 0;
for (uint32_t i = 0; i < item->meta->items.count; ++i) {
if (item->meta->items.item[i]->dimgForID == item->id) {
++dimgItemCount;
}
}
AVIF_CHECKERR(dimgItemCount == grid->rows * grid->columns, AVIF_RESULT_INVALID_IMAGE_GRID);
} else {
// item was generated for convenience and is not part of the bitstream.
// grid information should already be set.
AVIF_ASSERT_OR_RETURN(grid->rows > 0 && grid->columns > 0);
}
*codecType = avifDecoderItemGetGridCodecType(item);
AVIF_CHECKERR(*codecType != AVIF_CODEC_TYPE_UNKNOWN, AVIF_RESULT_INVALID_IMAGE_GRID);
} else {
*codecType = avifGetCodecType(item->type);
AVIF_ASSERT_OR_RETURN(*codecType != AVIF_CODEC_TYPE_UNKNOWN);
}
return AVIF_RESULT_OK;
}
static avifBool avifParseImageSpatialExtentsProperty(avifProperty * prop, const uint8_t * raw, size_t rawLen, avifDiagnostics * diag)
{
BEGIN_STREAM(s, raw, rawLen, diag, "Box[ispe]");
AVIF_CHECK(avifROStreamReadAndEnforceVersion(&s, /*enforcedVersion=*/0, /*flags=*/NULL));
avifImageSpatialExtents * ispe = &prop->u.ispe;
AVIF_CHECK(avifROStreamReadU32(&s, &ispe->width));
AVIF_CHECK(avifROStreamReadU32(&s, &ispe->height));
return AVIF_TRUE;
}
static avifBool avifParseAuxiliaryTypeProperty(avifProperty * prop, const uint8_t * raw, size_t rawLen, avifDiagnostics * diag)
{
BEGIN_STREAM(s, raw, rawLen, diag, "Box[auxC]");
AVIF_CHECK(avifROStreamReadAndEnforceVersion(&s, /*enforcedVersion=*/0, /*flags=*/NULL));
AVIF_CHECK(avifROStreamReadString(&s, prop->u.auxC.auxType, AUXTYPE_SIZE));
return AVIF_TRUE;
}
static avifBool avifParseColourInformationBox(avifProperty * prop, uint64_t rawOffset, const uint8_t * raw, size_t rawLen, avifDiagnostics * diag)
{
BEGIN_STREAM(s, raw, rawLen, diag, "Box[colr]");
avifColourInformationBox * colr = &prop->u.colr;
colr->hasICC = AVIF_FALSE;
colr->hasNCLX = AVIF_FALSE;
uint8_t colorType[4]; // unsigned int(32) colour_type;
AVIF_CHECK(avifROStreamRead(&s, colorType, 4));
if (!memcmp(colorType, "rICC", 4) || !memcmp(colorType, "prof", 4)) {
// Remember the offset of the ICC payload relative to the beginning of the stream. A direct pointer cannot be stored
// because decoder->io->persistent could have been AVIF_FALSE when obtaining raw through decoder->io->read().
// The bytes could be copied now instead of remembering the offset, but it is as invasive as passing rawOffset everywhere.
colr->iccOffset = rawOffset + avifROStreamOffset(&s);
colr->iccSize = avifROStreamRemainingBytes(&s);
if (colr->iccSize == 0) {
avifDiagnosticsPrintf(diag, "Box[colr] contains empty ICC_profile");
return AVIF_FALSE;
}
colr->hasICC = AVIF_TRUE;
} else if (!memcmp(colorType, "nclx", 4)) {
AVIF_CHECK(avifROStreamReadU16(&s, &colr->colorPrimaries)); // unsigned int(16) colour_primaries;
AVIF_CHECK(avifROStreamReadU16(&s, &colr->transferCharacteristics)); // unsigned int(16) transfer_characteristics;
AVIF_CHECK(avifROStreamReadU16(&s, &colr->matrixCoefficients)); // unsigned int(16) matrix_coefficients;
uint8_t full_range_flag;
AVIF_CHECK(avifROStreamReadBitsU8(&s, &full_range_flag, /*bitCount=*/1)); // unsigned int(1) full_range_flag;
colr->range = full_range_flag ? AVIF_RANGE_FULL : AVIF_RANGE_LIMITED;
uint8_t reserved;
AVIF_CHECK(avifROStreamReadBitsU8(&s, &reserved, /*bitCount=*/7)); // unsigned int(7) reserved = 0;
if (reserved) {
avifDiagnosticsPrintf(diag, "Box[colr] contains nonzero reserved bits [%u]", reserved);
return AVIF_FALSE;
}
colr->hasNCLX = AVIF_TRUE;
}
return AVIF_TRUE;
}
static avifResult avifParseContentLightLevelInformation(avifROStream * s, avifContentLightLevelInformationBox * clli)
{
AVIF_CHECKERR(avifROStreamReadBitsU16(s, &clli->maxCLL, 16), AVIF_RESULT_BMFF_PARSE_FAILED); // unsigned int(16) max_content_light_level
AVIF_CHECKERR(avifROStreamReadBitsU16(s, &clli->maxPALL, 16), AVIF_RESULT_BMFF_PARSE_FAILED); // unsigned int(16) max_pic_average_light_level
return AVIF_RESULT_OK;
}
static avifResult avifParseContentLightLevelInformationBox(avifProperty * prop, const uint8_t * raw, size_t rawLen, avifDiagnostics * diag)
{
BEGIN_STREAM(s, raw, rawLen, diag, "Box[clli]");
AVIF_CHECKRES(avifParseContentLightLevelInformation(&s, &prop->u.clli));
return AVIF_RESULT_OK;
}
#if defined(AVIF_ENABLE_EXPERIMENTAL_MINI)
static avifResult avifSkipMasteringDisplayColourVolume(avifROStream * s)
{
for (int c = 0; c < 3; c++) {
AVIF_CHECKERR(avifROStreamSkipBits(s, 16), AVIF_RESULT_BMFF_PARSE_FAILED); // unsigned int(16) display_primaries_x;
AVIF_CHECKERR(avifROStreamSkipBits(s, 16), AVIF_RESULT_BMFF_PARSE_FAILED); // unsigned int(16) display_primaries_y;
}
AVIF_CHECKERR(avifROStreamSkipBits(s, 16), AVIF_RESULT_BMFF_PARSE_FAILED); // unsigned int(16) white_point_x;
AVIF_CHECKERR(avifROStreamSkipBits(s, 16), AVIF_RESULT_BMFF_PARSE_FAILED); // unsigned int(16) white_point_y;
AVIF_CHECKERR(avifROStreamSkipBits(s, 32), AVIF_RESULT_BMFF_PARSE_FAILED); // unsigned int(32) max_display_mastering_luminance;
AVIF_CHECKERR(avifROStreamSkipBits(s, 32), AVIF_RESULT_BMFF_PARSE_FAILED); // unsigned int(32) min_display_mastering_luminance;
return AVIF_RESULT_OK;
}
static avifResult avifSkipContentColourVolume(avifROStream * s)
{
AVIF_CHECKERR(avifROStreamSkipBits(s, 1), AVIF_RESULT_BMFF_PARSE_FAILED); // unsigned int(1) reserved = 0; // ccv_cancel_flag
AVIF_CHECKERR(avifROStreamSkipBits(s, 1), AVIF_RESULT_BMFF_PARSE_FAILED); // unsigned int(1) reserved = 0; // ccv_persistence_flag
uint8_t ccvPrimariesPresent;
AVIF_CHECKERR(avifROStreamReadBitsU8(s, &ccvPrimariesPresent, 1), AVIF_RESULT_BMFF_PARSE_FAILED); // unsigned int(1) ccv_primaries_present_flag;
uint8_t ccvMinLuminanceValuePresent, ccvMaxLuminanceValuePresent, ccvAvgLuminanceValuePresent;
AVIF_CHECKERR(avifROStreamReadBitsU8(s, &ccvMinLuminanceValuePresent, 1),
AVIF_RESULT_BMFF_PARSE_FAILED); // unsigned int(1) ccv_min_luminance_value_present_flag;
AVIF_CHECKERR(avifROStreamReadBitsU8(s, &ccvMaxLuminanceValuePresent, 1),
AVIF_RESULT_BMFF_PARSE_FAILED); // unsigned int(1) ccv_max_luminance_value_present_flag;
AVIF_CHECKERR(avifROStreamReadBitsU8(s, &ccvAvgLuminanceValuePresent, 1),
AVIF_RESULT_BMFF_PARSE_FAILED); // unsigned int(1) ccv_avg_luminance_value_present_flag;
AVIF_CHECKERR(avifROStreamSkipBits(s, 2), AVIF_RESULT_BMFF_PARSE_FAILED); // unsigned int(2) reserved = 0;
if (ccvPrimariesPresent) {
for (int c = 0; c < 3; c++) {
AVIF_CHECKERR(avifROStreamSkipBits(s, 32), AVIF_RESULT_BMFF_PARSE_FAILED); // signed int(32) ccv_primaries_x[[c]];
AVIF_CHECKERR(avifROStreamSkipBits(s, 32), AVIF_RESULT_BMFF_PARSE_FAILED); // signed int(32) ccv_primaries_y[[c]];
}
}
if (ccvMinLuminanceValuePresent) {
AVIF_CHECKERR(avifROStreamSkipBits(s, 32), AVIF_RESULT_BMFF_PARSE_FAILED); // unsigned int(32) ccv_min_luminance_value;
}
if (ccvMaxLuminanceValuePresent) {
AVIF_CHECKERR(avifROStreamSkipBits(s, 32), AVIF_RESULT_BMFF_PARSE_FAILED); // unsigned int(32) ccv_max_luminance_value;
}
if (ccvAvgLuminanceValuePresent) {
AVIF_CHECKERR(avifROStreamSkipBits(s, 32), AVIF_RESULT_BMFF_PARSE_FAILED); // unsigned int(32) ccv_avg_luminance_value;
}
return AVIF_RESULT_OK;
}
static avifResult avifSkipAmbientViewingEnvironment(avifROStream * s)
{
AVIF_CHECKERR(avifROStreamSkipBits(s, 32), AVIF_RESULT_BMFF_PARSE_FAILED); // unsigned int(32) ambient_illuminance;
AVIF_CHECKERR(avifROStreamSkipBits(s, 16), AVIF_RESULT_BMFF_PARSE_FAILED); // unsigned int(16) ambient_light_x;
AVIF_CHECKERR(avifROStreamSkipBits(s, 16), AVIF_RESULT_BMFF_PARSE_FAILED); // unsigned int(16) ambient_light_y;
return AVIF_RESULT_OK;
}
static avifResult avifSkipReferenceViewingEnvironment(avifROStream * s)
{
AVIF_CHECKERR(avifROStreamSkipBits(s, 32), AVIF_RESULT_BMFF_PARSE_FAILED); // unsigned int(32) surround_luminance;
AVIF_CHECKERR(avifROStreamSkipBits(s, 16), AVIF_RESULT_BMFF_PARSE_FAILED); // unsigned int(16) surround_light_x;
AVIF_CHECKERR(avifROStreamSkipBits(s, 16), AVIF_RESULT_BMFF_PARSE_FAILED); // unsigned int(16) surround_light_y;
AVIF_CHECKERR(avifROStreamSkipBits(s, 32), AVIF_RESULT_BMFF_PARSE_FAILED); // unsigned int(32) periphery_luminance;
AVIF_CHECKERR(avifROStreamSkipBits(s, 16), AVIF_RESULT_BMFF_PARSE_FAILED); // unsigned int(16) periphery_light_x;
AVIF_CHECKERR(avifROStreamSkipBits(s, 16), AVIF_RESULT_BMFF_PARSE_FAILED); // unsigned int(16) periphery_light_y;
return AVIF_RESULT_OK;
}
static avifResult avifSkipNominalDiffuseWhite(avifROStream * s)
{
AVIF_CHECKERR(avifROStreamSkipBits(s, 32), AVIF_RESULT_BMFF_PARSE_FAILED); // unsigned int(32) diffuse_white_luminance;
return AVIF_RESULT_OK;
}
static avifResult avifParseMiniHDRProperties(avifROStream * s, uint32_t * hasClli, avifContentLightLevelInformationBox * clli)
{
AVIF_CHECKERR(avifROStreamReadBitsU32(s, hasClli, 1), AVIF_RESULT_BMFF_PARSE_FAILED); // bit(1) clli_flag;
uint32_t hasMdcv, hasCclv, hasAmve, hasReve, hasNdwt;
AVIF_CHECKERR(avifROStreamReadBitsU32(s, &hasMdcv, 1), AVIF_RESULT_BMFF_PARSE_FAILED); // bit(1) mdcv_flag;
AVIF_CHECKERR(avifROStreamReadBitsU32(s, &hasCclv, 1), AVIF_RESULT_BMFF_PARSE_FAILED); // bit(1) cclv_flag;
AVIF_CHECKERR(avifROStreamReadBitsU32(s, &hasAmve, 1), AVIF_RESULT_BMFF_PARSE_FAILED); // bit(1) amve_flag;
AVIF_CHECKERR(avifROStreamReadBitsU32(s, &hasReve, 1), AVIF_RESULT_BMFF_PARSE_FAILED); // bit(1) reve_flag;
AVIF_CHECKERR(avifROStreamReadBitsU32(s, &hasNdwt, 1), AVIF_RESULT_BMFF_PARSE_FAILED); // bit(1) ndwt_flag;
if (*hasClli) {
AVIF_CHECKRES(avifParseContentLightLevelInformation(s, clli)); // ContentLightLevel clli;
}
if (hasMdcv) {
AVIF_CHECKRES(avifSkipMasteringDisplayColourVolume(s)); // MasteringDisplayColourVolume mdcv;
}
if (hasCclv) {
AVIF_CHECKRES(avifSkipContentColourVolume(s)); // ContentColourVolume cclv;
}
if (hasAmve) {
AVIF_CHECKRES(avifSkipAmbientViewingEnvironment(s)); // AmbientViewingEnvironment amve;
}
if (hasReve) {
AVIF_CHECKRES(avifSkipReferenceViewingEnvironment(s)); // ReferenceViewingEnvironment reve;
}
if (hasNdwt) {
AVIF_CHECKRES(avifSkipNominalDiffuseWhite(s)); // NominalDiffuseWhite ndwt;
}
return AVIF_RESULT_OK;
}
#endif // AVIF_ENABLE_EXPERIMENTAL_MINI
// Implementation of section 2.3.3 of AV1 Codec ISO Media File Format Binding specification v1.2.0.
// See https://aomediacodec.github.io/av1-isobmff/v1.2.0.html#av1codecconfigurationbox-syntax.
static avifBool avifParseCodecConfiguration(avifROStream * s, avifCodecConfigurationBox * config, const char * configPropName, avifDiagnostics * diag)
{
const size_t av1COffset = s->offset;
uint32_t marker, version;
AVIF_CHECK(avifROStreamReadBitsU32(s, &marker, /*bitCount=*/1)); // unsigned int (1) marker = 1;
if (!marker) {
avifDiagnosticsPrintf(diag, "%.4s contains illegal marker: [%u]", configPropName, marker);
return AVIF_FALSE;
}
AVIF_CHECK(avifROStreamReadBitsU32(s, &version, /*bitCount=*/7)); // unsigned int (7) version = 1;
if (version != 1) {
avifDiagnosticsPrintf(diag, "%.4s contains illegal version: [%u]", configPropName, version);
return AVIF_FALSE;
}
AVIF_CHECK(avifROStreamReadBitsU8(s, &config->seqProfile, /*bitCount=*/3)); // unsigned int (3) seq_profile;
AVIF_CHECK(avifROStreamReadBitsU8(s, &config->seqLevelIdx0, /*bitCount=*/5)); // unsigned int (5) seq_level_idx_0;
AVIF_CHECK(avifROStreamReadBitsU8(s, &config->seqTier0, /*bitCount=*/1)); // unsigned int (1) seq_tier_0;
AVIF_CHECK(avifROStreamReadBitsU8(s, &config->highBitdepth, /*bitCount=*/1)); // unsigned int (1) high_bitdepth;
AVIF_CHECK(avifROStreamReadBitsU8(s, &config->twelveBit, /*bitCount=*/1)); // unsigned int (1) twelve_bit;
AVIF_CHECK(avifROStreamReadBitsU8(s, &config->monochrome, /*bitCount=*/1)); // unsigned int (1) monochrome;
AVIF_CHECK(avifROStreamReadBitsU8(s, &config->chromaSubsamplingX, /*bitCount=*/1)); // unsigned int (1) chroma_subsampling_x;
AVIF_CHECK(avifROStreamReadBitsU8(s, &config->chromaSubsamplingY, /*bitCount=*/1)); // unsigned int (1) chroma_subsampling_y;
AVIF_CHECK(avifROStreamReadBitsU8(s, &config->chromaSamplePosition, /*bitCount=*/2)); // unsigned int (2) chroma_sample_position;
// unsigned int (3) reserved = 0;
// unsigned int (1) initial_presentation_delay_present;
// if (initial_presentation_delay_present) {
// unsigned int (4) initial_presentation_delay_minus_one;
// } else {
// unsigned int (4) reserved = 0;
// }
AVIF_CHECK(avifROStreamSkip(s, /*byteCount=*/1));
// According to section 2.2.1 of AV1 Image File Format specification v1.1.0:
// - Sequence Header OBUs should not be present in the AV1CodecConfigurationBox.
// - If a Sequence Header OBU is present in the AV1CodecConfigurationBox,
// it shall match the Sequence Header OBU in the AV1 Image Item Data.
// - Metadata OBUs, if present, shall match the values given in other item properties,
// such as the PixelInformationProperty or ColourInformationBox.
// See https://aomediacodec.github.io/av1-avif/v1.1.0.html#av1-configuration-item-property.
// For simplicity, the constraints above are not enforced.
// The following is skipped by avifParseItemPropertyContainerBox().
// unsigned int (8) configOBUs[];
AVIF_CHECK(s->offset - av1COffset == 4); // Make sure avifParseCodecConfiguration() reads exactly 4 bytes.
return AVIF_TRUE;
}
static avifBool avifParseCodecConfigurationBoxProperty(avifProperty * prop,
const uint8_t * raw,
size_t rawLen,
const char * configPropName,
avifDiagnostics * diag)
{
char diagContext[10];
snprintf(diagContext, sizeof(diagContext), "Box[%.4s]", configPropName); // "Box[av1C]" or "Box[av2C]"
BEGIN_STREAM(s, raw, rawLen, diag, diagContext);
return avifParseCodecConfiguration(&s, &prop->u.av1C, configPropName, diag);
}
static avifBool avifParsePixelAspectRatioBoxProperty(avifProperty * prop, const uint8_t * raw, size_t rawLen, avifDiagnostics * diag)
{
BEGIN_STREAM(s, raw, rawLen, diag, "Box[pasp]");
avifPixelAspectRatioBox * pasp = &prop->u.pasp;
AVIF_CHECK(avifROStreamReadU32(&s, &pasp->hSpacing)); // unsigned int(32) hSpacing;
AVIF_CHECK(avifROStreamReadU32(&s, &pasp->vSpacing)); // unsigned int(32) vSpacing;
return AVIF_TRUE;
}
static avifBool avifParseCleanApertureBoxProperty(avifProperty * prop, const uint8_t * raw, size_t rawLen, avifDiagnostics * diag)
{
BEGIN_STREAM(s, raw, rawLen, diag, "Box[clap]");
avifCleanApertureBox * clap = &prop->u.clap;
AVIF_CHECK(avifROStreamReadU32(&s, &clap->widthN)); // unsigned int(32) cleanApertureWidthN;
AVIF_CHECK(avifROStreamReadU32(&s, &clap->widthD)); // unsigned int(32) cleanApertureWidthD;
AVIF_CHECK(avifROStreamReadU32(&s, &clap->heightN)); // unsigned int(32) cleanApertureHeightN;
AVIF_CHECK(avifROStreamReadU32(&s, &clap->heightD)); // unsigned int(32) cleanApertureHeightD;
AVIF_CHECK(avifROStreamReadU32(&s, &clap->horizOffN)); // unsigned int(32) horizOffN;
AVIF_CHECK(avifROStreamReadU32(&s, &clap->horizOffD)); // unsigned int(32) horizOffD;
AVIF_CHECK(avifROStreamReadU32(&s, &clap->vertOffN)); // unsigned int(32) vertOffN;
AVIF_CHECK(avifROStreamReadU32(&s, &clap->vertOffD)); // unsigned int(32) vertOffD;
return AVIF_TRUE;
}
static avifBool avifParseImageRotationProperty(avifProperty * prop, const uint8_t * raw, size_t rawLen, avifDiagnostics * diag)
{
BEGIN_STREAM(s, raw, rawLen, diag, "Box[irot]");
avifImageRotation * irot = &prop->u.irot;
uint8_t reserved;
AVIF_CHECK(avifROStreamReadBitsU8(&s, &reserved, /*bitCount=*/6)); // unsigned int (6) reserved = 0;
if (reserved) {
avifDiagnosticsPrintf(diag, "Box[irot] contains nonzero reserved bits [%u]", reserved);
return AVIF_FALSE;
}
AVIF_CHECK(avifROStreamReadBitsU8(&s, &irot->angle, /*bitCount=*/2)); // unsigned int (2) angle;
return AVIF_TRUE;
}
static avifBool avifParseImageMirrorProperty(avifProperty * prop, const uint8_t * raw, size_t rawLen, avifDiagnostics * diag)
{
BEGIN_STREAM(s, raw, rawLen, diag, "Box[imir]");
avifImageMirror * imir = &prop->u.imir;
uint8_t reserved;
AVIF_CHECK(avifROStreamReadBitsU8(&s, &reserved, /*bitCount=*/7)); // unsigned int(7) reserved = 0;
if (reserved) {
avifDiagnosticsPrintf(diag, "Box[imir] contains nonzero reserved bits [%u]", reserved);
return AVIF_FALSE;
}
AVIF_CHECK(avifROStreamReadBitsU8(&s, &imir->axis, /*bitCount=*/1)); // unsigned int(1) axis;
return AVIF_TRUE;
}
static avifResult avifParsePixelInformationProperty(avifProperty * prop, const uint8_t * raw, size_t rawLen, avifDiagnostics * diag)
{
BEGIN_STREAM(s, raw, rawLen, diag, "Box[pixi]");
uint32_t flags = 0; // px_flags
AVIF_CHECKERR(avifROStreamReadAndEnforceVersion(&s, /*enforcedVersion=*/0, &flags), AVIF_RESULT_BMFF_PARSE_FAILED);
avifPixelInformationProperty * pixi = &prop->u.pixi;
AVIF_CHECKERR(avifROStreamRead(&s, &pixi->planeCount, 1), AVIF_RESULT_BMFF_PARSE_FAILED); // unsigned int (8) num_channels;
if (pixi->planeCount < 1 || pixi->planeCount > MAX_PIXI_PLANE_DEPTHS) {
avifDiagnosticsPrintf(diag, "Box[pixi] contains unsupported plane count [%u]", pixi->planeCount);
return AVIF_RESULT_NOT_IMPLEMENTED;
}
for (uint8_t i = 0; i < pixi->planeCount; ++i) {
AVIF_CHECKERR(avifROStreamRead(&s, &pixi->planeDepths[i], 1), AVIF_RESULT_BMFF_PARSE_FAILED); // unsigned int (8) bits_per_channel;
if (pixi->planeDepths[i] == 0) {
avifDiagnosticsPrintf(diag, "Box[pixi] plane depth shall not be 0 for channel %u", i);
return AVIF_RESULT_BMFF_PARSE_FAILED;
}
if (pixi->planeDepths[i] > 16) {
avifDiagnosticsPrintf(diag, "Box[pixi] plane depth %d is not supported", (int)pixi->planeDepths[i]);
return AVIF_RESULT_NOT_IMPLEMENTED;
}
if (pixi->planeDepths[i] != pixi->planeDepths[0]) {
avifDiagnosticsPrintf(diag,
"Box[pixi] contains unsupported mismatched plane depths [%u != %u]",
pixi->planeDepths[i],
pixi->planeDepths[0]);
return AVIF_RESULT_NOT_IMPLEMENTED;
}
}
#if defined(AVIF_ENABLE_EXPERIMENTAL_EXTENDED_PIXI)
if (flags & 1) {
for (uint8_t i = 0; i < pixi->planeCount; ++i) {
uint8_t channelIdc, reserved, componentFormat, channelLabelFlag;
AVIF_CHECKERR(avifROStreamReadBitsU8(&s, &channelIdc, /*bitCount=*/3), AVIF_RESULT_BMFF_PARSE_FAILED); // unsigned int(3) channel_idc;
AVIF_CHECKERR(avifROStreamReadBitsU8(&s, &reserved, /*bitCount=*/1), AVIF_RESULT_BMFF_PARSE_FAILED); // unsigned int(1) reserved = 0;
AVIF_CHECKERR(avifROStreamReadBitsU8(&s, &componentFormat, /*bitCount=*/2), AVIF_RESULT_BMFF_PARSE_FAILED); // unsigned int(2) component_format;
AVIF_CHECKERR(avifROStreamReadBitsU8(&s, &pixi->subsamplingFlag[i], /*bitCount=*/1),
AVIF_RESULT_BMFF_PARSE_FAILED); // unsigned int(1) subsampling_flag;
AVIF_CHECKERR(avifROStreamReadBitsU8(&s, &channelLabelFlag, /*bitCount=*/1),
AVIF_RESULT_BMFF_PARSE_FAILED); // unsigned int(1) channel_label_flag;
if (pixi->subsamplingFlag[i]) {
AVIF_CHECKERR(avifROStreamReadBitsU8(&s, &pixi->subsamplingType[i], /*bitCount=*/4),
AVIF_RESULT_BMFF_PARSE_FAILED); // unsigned int(4) subsampling_type;
AVIF_CHECKERR(avifROStreamReadBitsU8(&s, &pixi->subsamplingLocation[i], /*bitCount=*/4),
AVIF_RESULT_BMFF_PARSE_FAILED); // unsigned int(4) subsampling_location;
}
// ISO/IEC 23008-12:2024/CDAM 2:2025 section 6.5.6.3:
// This field indicates the contents of the channel. A value of 0 indicates colour/grayscale. A value of
// 1 indicates alpha. A value of 2 indicates depth. Values 3-7 are reserved for future use. At most one
// channel shall have a channel_idc of 1.
if (channelIdc != 0) {
avifDiagnosticsPrintf(diag, "Box[pixi] contains unsupported channel_idc %u for channel %u", channelIdc, i);
return AVIF_RESULT_NOT_IMPLEMENTED;
}
if (reserved != 0) {
avifDiagnosticsPrintf(diag, "Box[pixi] contains non-zero reserved field %u for channel %u", reserved, i);
return AVIF_RESULT_BMFF_PARSE_FAILED;
}
// ISO/IEC 23008-12:2024/CDAM 2:2025 section 6.5.6.3:
// component_format: This field indicates the data type of the channel as defined by the component_format
// values in ISO/IEC 23001-17 where component_bit_depth is considered to be equal to bits_per_channel.
// ISO/IEC 23001-17 section 5.2.1.2:
// component_format: When equal to 0, component value is an unsigned integer coded on component_bit_depth bits.
if (componentFormat != 0) {
avifDiagnosticsPrintf(diag, "Box[pixi] contains unsupported component_format %u for channel %u", componentFormat, i);
return AVIF_RESULT_NOT_IMPLEMENTED;
}
if (pixi->subsamplingFlag[i]) {
if (pixi->subsamplingType[i] >= AVIF_PIXI_SUBSAMPLING_RESERVED) {
avifDiagnosticsPrintf(diag,
"Box[pixi] contains reserved subsampling_type %u for channel %u",
pixi->subsamplingType[i],
i);
return AVIF_RESULT_BMFF_PARSE_FAILED;
}
if (pixi->subsamplingLocation[i] > 4) {
avifDiagnosticsPrintf(diag,
"Box[pixi] contains reserved subsampling_location %u for channel %u",
pixi->subsamplingLocation[i],
i);
return AVIF_RESULT_BMFF_PARSE_FAILED;
}
}
if (channelLabelFlag) {
AVIF_CHECKERR(avifROStreamReadString(&s, NULL, 0), AVIF_RESULT_BMFF_PARSE_FAILED); // utf8string channel_label; (skipped)
}
}
}
#endif // AVIF_ENABLE_EXPERIMENTAL_EXTENDED_PIXI
return AVIF_RESULT_OK;
}
static avifBool avifParseOperatingPointSelectorProperty(avifProperty * prop, const uint8_t * raw, size_t rawLen, avifDiagnostics * diag)
{
BEGIN_STREAM(s, raw, rawLen, diag, "Box[a1op]");
avifOperatingPointSelectorProperty * a1op = &prop->u.a1op;
AVIF_CHECK(avifROStreamRead(&s, &a1op->opIndex, 1));
if (a1op->opIndex > 31) { // 31 is AV1's max operating point value
avifDiagnosticsPrintf(diag, "Box[a1op] contains an unsupported operating point [%u]", a1op->opIndex);
return AVIF_FALSE;
}
return AVIF_TRUE;
}
static avifBool avifParseLayerSelectorProperty(avifProperty * prop, const uint8_t * raw, size_t rawLen, avifDiagnostics * diag)
{
BEGIN_STREAM(s, raw, rawLen, diag, "Box[lsel]");
avifLayerSelectorProperty * lsel = &prop->u.lsel;
AVIF_CHECK(avifROStreamReadU16(&s, &lsel->layerID));
if ((lsel->layerID != 0xFFFF) && (lsel->layerID >= AVIF_MAX_AV1_LAYER_COUNT)) {
avifDiagnosticsPrintf(diag, "Box[lsel] contains an unsupported layer [%u]", lsel->layerID);
return AVIF_FALSE;
}
return AVIF_TRUE;
}
static avifBool avifParseAV1LayeredImageIndexingProperty(avifProperty * prop, const uint8_t * raw, size_t rawLen, avifDiagnostics * diag)
{
BEGIN_STREAM(s, raw, rawLen, diag, "Box[a1lx]");
avifAV1LayeredImageIndexingProperty * a1lx = &prop->u.a1lx;
uint8_t largeSize = 0;
AVIF_CHECK(avifROStreamRead(&s, &largeSize, 1));
if (largeSize & 0xFE) {
avifDiagnosticsPrintf(diag, "Box[a1lx] has bits set in the reserved section [%u]", largeSize);
return AVIF_FALSE;
}
for (int i = 0; i < 3; ++i) {
if (largeSize) {
AVIF_CHECK(avifROStreamReadU32(&s, &a1lx->layerSize[i]));
} else {
uint16_t layerSize16;
AVIF_CHECK(avifROStreamReadU16(&s, &layerSize16));
a1lx->layerSize[i] = (uint32_t)layerSize16;
}
}
// Layer sizes will be validated later (when the item's size is known)
return AVIF_TRUE;
}
static avifResult avifParseItemPropertyContainerBox(avifPropertyArray * properties,
uint64_t rawOffset,
const uint8_t * raw,
size_t rawLen,
avifBool isTrack,
avifDiagnostics * diag)
{
BEGIN_STREAM(s, raw, rawLen, diag, "Box[ipco]");
while (avifROStreamHasBytesLeft(&s, 1)) {
avifBoxHeader header;
AVIF_CHECKERR(avifROStreamReadBoxHeader(&s, &header), AVIF_RESULT_BMFF_PARSE_FAILED);
avifProperty * prop = (avifProperty *)avifArrayPush(properties);
AVIF_CHECKERR(prop != NULL, AVIF_RESULT_OUT_OF_MEMORY);
memcpy(prop->type, header.type, 4);
prop->isOpaque = AVIF_FALSE;
if (!memcmp(header.type, "ispe", 4)) {
AVIF_CHECKERR(avifParseImageSpatialExtentsProperty(prop, avifROStreamCurrent(&s), header.size, diag),
AVIF_RESULT_BMFF_PARSE_FAILED);
} else if ((!memcmp(header.type, "auxC", 4) && !isTrack) || (!memcmp(header.type, "auxi", 4) && isTrack)) {
AVIF_CHECKERR(avifParseAuxiliaryTypeProperty(prop, avifROStreamCurrent(&s), header.size, diag), AVIF_RESULT_BMFF_PARSE_FAILED);
} else if (!memcmp(header.type, "colr", 4)) {
AVIF_CHECKERR(avifParseColourInformationBox(prop, rawOffset + avifROStreamOffset(&s), avifROStreamCurrent(&s), header.size, diag),
AVIF_RESULT_BMFF_PARSE_FAILED);
} else if (!memcmp(header.type, "av1C", 4)) {
AVIF_CHECKERR(avifParseCodecConfigurationBoxProperty(prop, avifROStreamCurrent(&s), header.size, "av1C", diag),
AVIF_RESULT_BMFF_PARSE_FAILED);
#if defined(AVIF_CODEC_AVM)
} else if (!memcmp(header.type, "av2C", 4)) {
AVIF_CHECKERR(avifParseCodecConfigurationBoxProperty(prop, avifROStreamCurrent(&s), header.size, "av2C", diag),
AVIF_RESULT_BMFF_PARSE_FAILED);
#endif
} else if (!memcmp(header.type, "pasp", 4)) {
AVIF_CHECKERR(avifParsePixelAspectRatioBoxProperty(prop, avifROStreamCurrent(&s), header.size, diag),
AVIF_RESULT_BMFF_PARSE_FAILED);
} else if (!memcmp(header.type, "clap", 4)) {
AVIF_CHECKERR(avifParseCleanApertureBoxProperty(prop, avifROStreamCurrent(&s), header.size, diag),
AVIF_RESULT_BMFF_PARSE_FAILED);
} else if (!memcmp(header.type, "irot", 4)) {
AVIF_CHECKERR(avifParseImageRotationProperty(prop, avifROStreamCurrent(&s), header.size, diag), AVIF_RESULT_BMFF_PARSE_FAILED);
} else if (!memcmp(header.type, "imir", 4)) {
AVIF_CHECKERR(avifParseImageMirrorProperty(prop, avifROStreamCurrent(&s), header.size, diag), AVIF_RESULT_BMFF_PARSE_FAILED);
} else if (!memcmp(header.type, "pixi", 4)) {
AVIF_CHECKRES(avifParsePixelInformationProperty(prop, avifROStreamCurrent(&s), header.size, diag));
} else if (!memcmp(header.type, "a1op", 4)) {
AVIF_CHECKERR(avifParseOperatingPointSelectorProperty(prop, avifROStreamCurrent(&s), header.size, diag),
AVIF_RESULT_BMFF_PARSE_FAILED);
} else if (!memcmp(header.type, "lsel", 4)) {
AVIF_CHECKERR(avifParseLayerSelectorProperty(prop, avifROStreamCurrent(&s), header.size, diag), AVIF_RESULT_BMFF_PARSE_FAILED);
} else if (!memcmp(header.type, "a1lx", 4)) {
AVIF_CHECKERR(avifParseAV1LayeredImageIndexingProperty(prop, avifROStreamCurrent(&s), header.size, diag),
AVIF_RESULT_BMFF_PARSE_FAILED);
} else if (!memcmp(header.type, "clli", 4)) {
AVIF_CHECKRES(avifParseContentLightLevelInformationBox(prop, avifROStreamCurrent(&s), header.size, diag));
} else {
prop->isOpaque = AVIF_TRUE;
memset(&prop->u.opaque, 0, sizeof(prop->u.opaque));
memcpy(prop->u.opaque.usertype, header.usertype, sizeof(prop->u.opaque.usertype));
AVIF_CHECKRES(avifRWDataSet(&prop->u.opaque.boxPayload, avifROStreamCurrent(&s), header.size));
}
AVIF_CHECKERR(avifROStreamSkip(&s, header.size), AVIF_RESULT_BMFF_PARSE_FAILED);
}
return AVIF_RESULT_OK;
}
static avifResult avifParseItemPropertyAssociation(avifMeta * meta, const uint8_t * raw, size_t rawLen, avifDiagnostics * diag, uint32_t * outVersionAndFlags)
{
// NOTE: If this function ever adds support for versions other than [0,1] or flags other than
// [0,1], please increase the value of MAX_IPMA_VERSION_AND_FLAGS_SEEN accordingly.
BEGIN_STREAM(s, raw, rawLen, diag, "Box[ipma]");
uint8_t version;
uint32_t flags;
AVIF_CHECKERR(avifROStreamReadVersionAndFlags(&s, &version, &flags), AVIF_RESULT_BMFF_PARSE_FAILED);
avifBool propertyIndexIsU15 = ((flags & 0x1) != 0);
*outVersionAndFlags = ((uint32_t)version << 24) | flags;
uint32_t entryCount;
AVIF_CHECKERR(avifROStreamReadU32(&s, &entryCount), AVIF_RESULT_BMFF_PARSE_FAILED);
unsigned int prevItemID = 0;
for (uint32_t entryIndex = 0; entryIndex < entryCount; ++entryIndex) {
// ISO/IEC 14496-12, Seventh edition, 2022-01, Section 8.11.14.1:
// Each ItemPropertyAssociationBox shall be ordered by increasing item_ID, and there shall
// be at most one occurrence of a given item_ID, in the set of ItemPropertyAssociationBox
// boxes.
unsigned int itemID;
if (version < 1) {
uint16_t tmp;
AVIF_CHECKERR(avifROStreamReadU16(&s, &tmp), AVIF_RESULT_BMFF_PARSE_FAILED);
itemID = tmp;
} else {
AVIF_CHECKERR(avifROStreamReadU32(&s, &itemID), AVIF_RESULT_BMFF_PARSE_FAILED);
}
AVIF_CHECKRES(avifCheckItemID("ipma", itemID, diag));
if (itemID <= prevItemID) {
avifDiagnosticsPrintf(diag, "Box[ipma] item IDs are not ordered by increasing ID");
return AVIF_RESULT_BMFF_PARSE_FAILED;
}
prevItemID = itemID;
avifDecoderItem * item;
AVIF_CHECKRES(avifMetaFindOrCreateItem(meta, itemID, &item));
if (item->ipmaSeen) {
avifDiagnosticsPrintf(diag, "Duplicate Box[ipma] for item ID [%u]", itemID);
return AVIF_RESULT_BMFF_PARSE_FAILED;
}
item->ipmaSeen = AVIF_TRUE;
uint8_t associationCount;
AVIF_CHECKERR(avifROStreamRead(&s, &associationCount, 1), AVIF_RESULT_BMFF_PARSE_FAILED);
for (uint8_t associationIndex = 0; associationIndex < associationCount; ++associationIndex) {
uint8_t essential;
AVIF_CHECKERR(avifROStreamReadBitsU8(&s, &essential, /*bitCount=*/1), AVIF_RESULT_BMFF_PARSE_FAILED); // bit(1) essential;
uint32_t propertyIndex;
AVIF_CHECKERR(avifROStreamReadBitsU32(&s, &propertyIndex, /*bitCount=*/propertyIndexIsU15 ? 15 : 7),
AVIF_RESULT_BMFF_PARSE_FAILED); // unsigned int(7/15) property_index;
// ISO/IEC 14496-12 Section 8.11.14.3:
// 0 indicating that no property is associated (the essential indicator shall also be 0)
if (propertyIndex == 0) {
if (essential) {
avifDiagnosticsPrintf(diag, "Box[ipma] for item ID [%u] contains an illegal essential property index 0", itemID);
return AVIF_RESULT_BMFF_PARSE_FAILED;
}
continue;
}
--propertyIndex; // 1-indexed
if (propertyIndex >= meta->properties.count) {
avifDiagnosticsPrintf(diag,
"Box[ipma] for item ID [%u] contains an illegal property index [%u] (out of [%u] properties)",
itemID,
propertyIndex,
meta->properties.count);
return AVIF_RESULT_BMFF_PARSE_FAILED;
}
// Copy property to item
const avifProperty * srcProp = &meta->properties.prop[propertyIndex];
// Some properties are supported and parsed by libavif.
// Other properties are forwarded to the user as opaque blobs.
const avifBool supportedType = !srcProp->isOpaque;
if (supportedType) {
if (essential) {
// Verify that it is legal for this property to be flagged as essential. Any
// types in this list are *required* in the spec to not be flagged as essential
// when associated with an item.
static const char * const nonessentialTypes[] = {
// AVIF: Section 2.3.2.3.2: "If associated, it shall not be marked as essential."
"a1lx"
};
size_t nonessentialTypesCount = sizeof(nonessentialTypes) / sizeof(nonessentialTypes[0]);
for (size_t i = 0; i < nonessentialTypesCount; ++i) {
if (!memcmp(srcProp->type, nonessentialTypes[i], 4)) {
avifDiagnosticsPrintf(diag,
"Item ID [%u] has a %s property association which must not be marked essential, but is",
itemID,
nonessentialTypes[i]);
return AVIF_RESULT_BMFF_PARSE_FAILED;
}
}
} else {
// Verify that it is legal for this property to not be flagged as essential. Any
// types in this list are *required* in the spec to be flagged as essential when
// associated with an item.
static const char * const essentialTypes[] = {
// AVIF: Section 2.3.2.1.1: "If associated, it shall be marked as essential."
"a1op",
// HEIF: Section 6.5.11.1: "essential shall be equal to 1 for an 'lsel' item property."
"lsel",
// MIAF 2019/Amd. 2:2021: Section 7.3.9:
// All transformative properties associated with coded and derived images shall be
// marked as essential
// It makes no sense to allow for non-essential crop/orientation associated with an item
// that is not a coded or derived image, so for simplicity 'item' is not checked here.
"clap",
"irot",
"imir"
};
size_t essentialTypesCount = sizeof(essentialTypes) / sizeof(essentialTypes[0]);
for (size_t i = 0; i < essentialTypesCount; ++i) {
if (!memcmp(srcProp->type, essentialTypes[i], 4)) {
avifDiagnosticsPrintf(diag,
"Item ID [%u] has a %s property association which must be marked essential, but is not",
itemID,
essentialTypes[i]);
return AVIF_RESULT_BMFF_PARSE_FAILED;
}
}
}
// Supported and valid; associate it with this item.
avifProperty * dstProp = (avifProperty *)avifArrayPush(&item->properties);
AVIF_CHECKERR(dstProp != NULL, AVIF_RESULT_OUT_OF_MEMORY);
*dstProp = *srcProp;
} else {
if (essential) {
// ISO/IEC 23008-12 Section 10.2.1:
// Under any brand, the primary item (or an alternative if alternative support is required)
// shall be processable by a reader implementing only the required features of that brand.
// Specifically, given that each brand has a set of properties that a reader is required to
// support: the item shall not have properties that are marked as essential and are outside
// this set.
// It is assumed that this rule also applies to items the primary item depends on (such as
// the cells of a grid).
// Discovered an essential item property that libavif doesn't support!
// Make a note to ignore this item later.
item->hasUnsupportedEssentialProperty = AVIF_TRUE;
}
// Will be forwarded to the user through avifImage::properties.
avifProperty * dstProp = (avifProperty *)avifArrayPush(&item->properties);
AVIF_CHECKERR(dstProp != NULL, AVIF_RESULT_OUT_OF_MEMORY);
dstProp->isOpaque = AVIF_TRUE;
memcpy(dstProp->type, srcProp->type, sizeof(dstProp->type));
memcpy(dstProp->u.opaque.usertype, srcProp->u.opaque.usertype, sizeof(dstProp->u.opaque.usertype));
AVIF_CHECKRES(
avifRWDataSet(&dstProp->u.opaque.boxPayload, srcProp->u.opaque.boxPayload.data, srcProp->u.opaque.boxPayload.size));
}
}
}
return AVIF_RESULT_OK;
}
static avifBool avifParsePrimaryItemBox(avifMeta * meta, const uint8_t * raw, size_t rawLen, avifDiagnostics * diag)
{
if (meta->primaryItemID > 0) {
// Illegal to have multiple pitm boxes, bail out
avifDiagnosticsPrintf(diag, "Multiple boxes of unique Box[pitm] found");
return AVIF_FALSE;
}
BEGIN_STREAM(s, raw, rawLen, diag, "Box[pitm]");
uint8_t version;
AVIF_CHECK(avifROStreamReadVersionAndFlags(&s, &version, NULL));
if (version == 0) {
uint16_t tmp16;
AVIF_CHECK(avifROStreamReadU16(&s, &tmp16)); // unsigned int(16) item_ID;
meta->primaryItemID = tmp16;
} else {
AVIF_CHECK(avifROStreamReadU32(&s, &meta->primaryItemID)); // unsigned int(32) item_ID;
}
return AVIF_TRUE;
}
static avifBool avifParseItemDataBox(avifMeta * meta, const uint8_t * raw, size_t rawLen, avifDiagnostics * diag)
{
// Check to see if we've already seen an idat box for this meta box. If so, bail out
if (meta->idat.size > 0) {
avifDiagnosticsPrintf(diag, "Meta box contains multiple idat boxes");
return AVIF_FALSE;
}
if (rawLen == 0) {
avifDiagnosticsPrintf(diag, "idat box has a length of 0");
return AVIF_FALSE;
}
if (avifRWDataSet(&meta->idat, raw, rawLen) != AVIF_RESULT_OK) {
return AVIF_FALSE;
}
return AVIF_TRUE;
}
static avifResult avifParseItemPropertiesBox(avifMeta * meta, uint64_t rawOffset, const uint8_t * raw, size_t rawLen, avifDiagnostics * diag)
{
BEGIN_STREAM(s, raw, rawLen, diag, "Box[iprp]");
avifBoxHeader ipcoHeader;
AVIF_CHECKERR(avifROStreamReadBoxHeader(&s, &ipcoHeader), AVIF_RESULT_BMFF_PARSE_FAILED);
if (memcmp(ipcoHeader.type, "ipco", 4)) {
avifDiagnosticsPrintf(diag, "Failed to find Box[ipco] as the first box in Box[iprp]");
return AVIF_RESULT_BMFF_PARSE_FAILED;
}
// Read all item properties inside of ItemPropertyContainerBox
AVIF_CHECKRES(avifParseItemPropertyContainerBox(&meta->properties,
rawOffset + avifROStreamOffset(&s),
avifROStreamCurrent(&s),
ipcoHeader.size,
/*isTrack=*/AVIF_FALSE,
diag));
AVIF_CHECKERR(avifROStreamSkip(&s, ipcoHeader.size), AVIF_RESULT_BMFF_PARSE_FAILED);
uint32_t versionAndFlagsSeen[MAX_IPMA_VERSION_AND_FLAGS_SEEN];
uint32_t versionAndFlagsSeenCount = 0;
// Now read all ItemPropertyAssociation until the end of the box, and make associations
while (avifROStreamHasBytesLeft(&s, 1)) {
avifBoxHeader ipmaHeader;
AVIF_CHECKERR(avifROStreamReadBoxHeader(&s, &ipmaHeader), AVIF_RESULT_BMFF_PARSE_FAILED);
if (!memcmp(ipmaHeader.type, "ipma", 4)) {
uint32_t versionAndFlags;
AVIF_CHECKRES(avifParseItemPropertyAssociation(meta, avifROStreamCurrent(&s), ipmaHeader.size, diag, &versionAndFlags));
for (uint32_t i = 0; i < versionAndFlagsSeenCount; ++i) {
if (versionAndFlagsSeen[i] == versionAndFlags) {
// BMFF (ISO/IEC 14496-12:2022) 8.11.14.1 - There shall be at most one
// ItemPropertyAssociationBox with a given pair of values of version and
// flags.
avifDiagnosticsPrintf(diag, "Multiple Box[ipma] with a given pair of values of version and flags. See BMFF (ISO/IEC 14496-12:2022) 8.11.14.1");
return AVIF_RESULT_BMFF_PARSE_FAILED;
}
}
if (versionAndFlagsSeenCount == MAX_IPMA_VERSION_AND_FLAGS_SEEN) {
avifDiagnosticsPrintf(diag, "Exceeded possible count of unique ipma version and flags tuples");
return AVIF_RESULT_BMFF_PARSE_FAILED;
}
versionAndFlagsSeen[versionAndFlagsSeenCount] = versionAndFlags;
++versionAndFlagsSeenCount;
} else {
// These must all be type ipma
avifDiagnosticsPrintf(diag, "Box[iprp] contains a box that isn't type 'ipma'");
return AVIF_RESULT_BMFF_PARSE_FAILED;
}
AVIF_CHECKERR(avifROStreamSkip(&s, ipmaHeader.size), AVIF_RESULT_BMFF_PARSE_FAILED);
}
return AVIF_RESULT_OK;
}
static avifResult avifParseItemInfoEntry(avifMeta * meta, const uint8_t * raw, size_t rawLen, avifDiagnostics * diag)
{
// Section 8.11.6.2 of ISO/IEC 14496-12.
BEGIN_STREAM(s, raw, rawLen, diag, "Box[infe]");
uint8_t version;
uint32_t flags;
AVIF_CHECKERR(avifROStreamReadVersionAndFlags(&s, &version, &flags), AVIF_RESULT_BMFF_PARSE_FAILED);
// Version 2+ is required for item_type
if (version != 2 && version != 3) {
avifDiagnosticsPrintf(s.diag, "%s: Expecting box version 2 or 3, got version %u", s.diagContext, version);
return AVIF_RESULT_BMFF_PARSE_FAILED;
}
// Ignore flags&1. A value of 1 corresponds to a hidden image item (not intended to be displayed).
// There could be files wrongly setting that flag to 1 for items output as "to be displayed"
// by libavif so far, so keep that lenient behavior for simplicity and backward compatibility.
uint32_t itemID;
if (version == 2) {
uint16_t tmp;
AVIF_CHECKERR(avifROStreamReadU16(&s, &tmp), AVIF_RESULT_BMFF_PARSE_FAILED); // unsigned int(16) item_ID;
itemID = tmp;
} else {
AVIF_ASSERT_OR_RETURN(version == 3);
AVIF_CHECKERR(avifROStreamReadU32(&s, &itemID), AVIF_RESULT_BMFF_PARSE_FAILED); // unsigned int(32) item_ID;
}
AVIF_CHECKRES(avifCheckItemID("infe", itemID, diag));
uint16_t itemProtectionIndex;
AVIF_CHECKERR(avifROStreamReadU16(&s, &itemProtectionIndex), AVIF_RESULT_BMFF_PARSE_FAILED); // unsigned int(16) item_protection_index;
uint8_t itemType[4];
AVIF_CHECKERR(avifROStreamRead(&s, itemType, 4), AVIF_RESULT_BMFF_PARSE_FAILED); // unsigned int(32) item_type;
AVIF_CHECKERR(avifROStreamReadString(&s, NULL, 0), AVIF_RESULT_BMFF_PARSE_FAILED); // utf8string item_name; (skipped)
avifContentType contentType;
if (!memcmp(itemType, "mime", 4)) {
AVIF_CHECKERR(avifROStreamReadString(&s, contentType.contentType, CONTENTTYPE_SIZE), AVIF_RESULT_BMFF_PARSE_FAILED); // utf8string content_type;
// utf8string content_encoding; //optional
} else {
// if (item_type == 'uri ') {
// utf8string item_uri_type;
// }
memset(&contentType, 0, sizeof(contentType));
}
avifDecoderItem * item;
AVIF_CHECKRES(avifMetaFindOrCreateItem(meta, itemID, &item));
memcpy(item->type, itemType, sizeof(itemType));
item->contentType = contentType;
return AVIF_RESULT_OK;
}
static avifResult avifParseItemInfoBox(avifMeta * meta, const uint8_t * raw, size_t rawLen, avifDiagnostics * diag)
{
BEGIN_STREAM(s, raw, rawLen, diag, "Box[iinf]");
uint8_t version;
AVIF_CHECKERR(avifROStreamReadVersionAndFlags(&s, &version, NULL), AVIF_RESULT_BMFF_PARSE_FAILED);
uint32_t entryCount;
if (version == 0) {
uint16_t tmp;
AVIF_CHECKERR(avifROStreamReadU16(&s, &tmp), AVIF_RESULT_BMFF_PARSE_FAILED); // unsigned int(16) entry_count;
entryCount = tmp;
} else if (version == 1) {
AVIF_CHECKERR(avifROStreamReadU32(&s, &entryCount), AVIF_RESULT_BMFF_PARSE_FAILED); // unsigned int(32) entry_count;
} else {
avifDiagnosticsPrintf(diag, "Box[iinf] has an unsupported version %u", version);
return AVIF_RESULT_BMFF_PARSE_FAILED;
}
for (uint32_t entryIndex = 0; entryIndex < entryCount; ++entryIndex) {
avifBoxHeader infeHeader;
AVIF_CHECKERR(avifROStreamReadBoxHeader(&s, &infeHeader), AVIF_RESULT_BMFF_PARSE_FAILED);
if (!memcmp(infeHeader.type, "infe", 4)) {
AVIF_CHECKRES(avifParseItemInfoEntry(meta, avifROStreamCurrent(&s), infeHeader.size, diag));
} else {
// These must all be type infe
avifDiagnosticsPrintf(diag, "Box[iinf] contains a box that isn't type 'infe'");
return AVIF_RESULT_BMFF_PARSE_FAILED;
}
AVIF_CHECKERR(avifROStreamSkip(&s, infeHeader.size), AVIF_RESULT_BMFF_PARSE_FAILED);
}
return AVIF_RESULT_OK;
}
static avifResult avifParseItemReferenceBox(avifMeta * meta, const uint8_t * raw, size_t rawLen, avifDiagnostics * diag)
{
BEGIN_STREAM(s, raw, rawLen, diag, "Box[iref]");
uint8_t version;
AVIF_CHECKERR(avifROStreamReadVersionAndFlags(&s, &version, NULL), AVIF_RESULT_BMFF_PARSE_FAILED);
if (version > 1) {
// iref versions > 1 are not supported. Skip it.
return AVIF_RESULT_OK;
}
while (avifROStreamHasBytesLeft(&s, 1)) {
avifBoxHeader irefHeader;
AVIF_CHECKERR(avifROStreamReadBoxHeader(&s, &irefHeader), AVIF_RESULT_BMFF_PARSE_FAILED);
uint32_t fromID = 0;
if (version == 0) {
uint16_t tmp;
AVIF_CHECKERR(avifROStreamReadU16(&s, &tmp), AVIF_RESULT_BMFF_PARSE_FAILED); // unsigned int(16) from_item_ID;
fromID = tmp;
} else {
// version == 1
AVIF_CHECKERR(avifROStreamReadU32(&s, &fromID), AVIF_RESULT_BMFF_PARSE_FAILED); // unsigned int(32) from_item_ID;
}
// ISO 14496-12 section 8.11.12.1: "index values start at 1"
AVIF_CHECKRES(avifCheckItemID("iref", fromID, diag));
avifDecoderItem * item;
AVIF_CHECKRES(avifMetaFindOrCreateItem(meta, fromID, &item));
if (!memcmp(irefHeader.type, "dimg", 4)) {
if (item->hasDimgFrom) {
// ISO/IEC 23008-12 (HEIF) 6.6.1: The number of SingleItemTypeReferenceBoxes with the box type 'dimg'
// and with the same value of from_item_ID shall not be greater than 1.
avifDiagnosticsPrintf(diag, "Box[iinf] contains duplicate boxes of type 'dimg' with the same from_item_ID value %u", fromID);
return AVIF_RESULT_BMFF_PARSE_FAILED;
}
item->hasDimgFrom = AVIF_TRUE;
}
uint16_t referenceCount = 0;
AVIF_CHECKERR(avifROStreamReadU16(&s, &referenceCount), AVIF_RESULT_BMFF_PARSE_FAILED); // unsigned int(16) reference_count;
for (uint16_t refIndex = 0; refIndex < referenceCount; ++refIndex) {
uint32_t toID = 0;
if (version == 0) {
uint16_t tmp;
AVIF_CHECKERR(avifROStreamReadU16(&s, &tmp), AVIF_RESULT_BMFF_PARSE_FAILED); // unsigned int(16) to_item_ID;
toID = tmp;
} else {
// version == 1
AVIF_CHECKERR(avifROStreamReadU32(&s, &toID), AVIF_RESULT_BMFF_PARSE_FAILED); // unsigned int(32) to_item_ID;
}
AVIF_CHECKRES(avifCheckItemID("iref", toID, diag));
// Read this reference as "{fromID} is a {irefType} for {toID}"
if (!memcmp(irefHeader.type, "thmb", 4)) {
item->thumbnailForID = toID;
} else if (!memcmp(irefHeader.type, "auxl", 4)) {
item->auxForID = toID;
} else if (!memcmp(irefHeader.type, "cdsc", 4)) {
item->descForID = toID;
} else if (!memcmp(irefHeader.type, "dimg", 4)) {
// derived images refer in the opposite direction
avifDecoderItem * dimg;
AVIF_CHECKRES(avifMetaFindOrCreateItem(meta, toID, &dimg));
// Section 8.11.12.1 of ISO/IEC 14496-12:
// The items linked to are then represented by an array of to_item_IDs;
// within a given array, a given value shall occur at most once.
AVIF_CHECKERR(dimg->dimgForID != fromID, AVIF_RESULT_INVALID_IMAGE_GRID);
// A given value may occur within multiple arrays but this is not supported by libavif.
AVIF_CHECKERR(dimg->dimgForID == 0, AVIF_RESULT_NOT_IMPLEMENTED);
dimg->dimgForID = fromID;
dimg->dimgIdx = refIndex;
} else if (!memcmp(irefHeader.type, "prem", 4)) {
item->premByID = toID;
}
}
}
return AVIF_RESULT_OK;
}
static avifResult avifParseGroupsListBox(avifMeta * meta, const uint8_t * raw, size_t rawLen, avifDiagnostics * diag)
{
BEGIN_STREAM(s, raw, rawLen, diag, "Box[grpl]");
while (avifROStreamHasBytesLeft(&s, 1)) {
avifBoxHeader groupHeader;
AVIF_CHECKERR(avifROStreamReadBoxHeader(&s, &groupHeader), AVIF_RESULT_BMFF_PARSE_FAILED);
// We don't check the flag or version as they depend on the grouping type (and for simplicity).
// ISO/IEC 14496-12:2024 Section 8.15.3.2
// version shall be 0 unless defined otherwise for the grouping_type. Any values of flags such that
// (flags & 0x000FFF) is not equal to 0 are reserved. The values of flags shall be such that (flags
// & 0xFFF000) is equal to 0 unless defined otherwise for the grouping_type.
AVIF_CHECKERR(avifROStreamReadVersionAndFlags(&s, NULL, NULL), AVIF_RESULT_BMFF_PARSE_FAILED);
avifEntityToGroup * group = avifArrayPush(&meta->entityToGroups);
AVIF_CHECKERR(group != NULL, AVIF_RESULT_OUT_OF_MEMORY);
AVIF_CHECKERR(avifArrayCreate(&group->entityIDs, sizeof(uint32_t), 2), AVIF_RESULT_OUT_OF_MEMORY);
memcpy(group->groupingType, groupHeader.type, 4);
AVIF_CHECKERR(avifROStreamReadU32(&s, &group->groupID), AVIF_RESULT_BMFF_PARSE_FAILED);
uint32_t numEntitiesInGroup;
AVIF_CHECKERR(avifROStreamReadU32(&s, &numEntitiesInGroup), AVIF_RESULT_BMFF_PARSE_FAILED);
for (uint32_t i = 0; i < numEntitiesInGroup; ++i) {
uint32_t * entityId = avifArrayPush(&group->entityIDs);
AVIF_CHECKERR(entityId != NULL, AVIF_RESULT_OUT_OF_MEMORY);
AVIF_CHECKERR(avifROStreamReadU32(&s, entityId), AVIF_RESULT_BMFF_PARSE_FAILED);
}
}
return AVIF_RESULT_OK;
}
static avifResult avifParseMetaBox(avifMeta * meta, uint64_t rawOffset, const uint8_t * raw, size_t rawLen, avifDiagnostics * diag)
{
BEGIN_STREAM(s, raw, rawLen, diag, "Box[meta]");
uint32_t flags;
AVIF_CHECKERR(avifROStreamReadAndEnforceVersion(&s, 0, &flags), AVIF_RESULT_BMFF_PARSE_FAILED);
++meta->idatID; // for tracking idat
avifBool firstBox = AVIF_TRUE;
uint32_t uniqueBoxFlags = 0;
while (avifROStreamHasBytesLeft(&s, 1)) {
avifBoxHeader header;
AVIF_CHECKERR(avifROStreamReadBoxHeader(&s, &header), AVIF_RESULT_BMFF_PARSE_FAILED);
if (firstBox) {
if (!memcmp(header.type, "hdlr", 4)) {
uint8_t handlerType[4];
AVIF_CHECKERR(avifParseHandlerBox(avifROStreamCurrent(&s), header.size, handlerType, diag), AVIF_RESULT_BMFF_PARSE_FAILED);
// HEIF (ISO/IEC 23008-12:2022), Section 6.2:
// The handler type for the MetaBox shall be 'pict'.
if (memcmp(handlerType, "pict", 4) != 0) {
avifDiagnosticsPrintf(diag, "Box[hdlr] handler_type is not 'pict'");
return AVIF_RESULT_BMFF_PARSE_FAILED;
}
firstBox = AVIF_FALSE;
} else {
// hdlr must be the first box!
avifDiagnosticsPrintf(diag, "Box[meta] does not have a Box[hdlr] as its first child box");
return AVIF_RESULT_BMFF_PARSE_FAILED;
}
} else if (!memcmp(header.type, "hdlr", 4)) {
avifDiagnosticsPrintf(diag, "Box[meta] contains a duplicate unique box of type 'hdlr'");
return AVIF_RESULT_BMFF_PARSE_FAILED;
} else if (!memcmp(header.type, "iloc", 4)) {
AVIF_CHECKERR(uniqueBoxSeen(&uniqueBoxFlags, AVIF_UNIQUE_ILOC, "meta", "iloc", diag), AVIF_RESULT_BMFF_PARSE_FAILED);
AVIF_CHECKRES(avifParseItemLocationBox(meta, avifROStreamCurrent(&s), header.size, diag));
} else if (!memcmp(header.type, "pitm", 4)) {
AVIF_CHECKERR(uniqueBoxSeen(&uniqueBoxFlags, AVIF_UNIQUE_PITM, "meta", "pitm", diag), AVIF_RESULT_BMFF_PARSE_FAILED);
AVIF_CHECKERR(avifParsePrimaryItemBox(meta, avifROStreamCurrent(&s), header.size, diag), AVIF_RESULT_BMFF_PARSE_FAILED);
} else if (!memcmp(header.type, "idat", 4)) {
AVIF_CHECKERR(uniqueBoxSeen(&uniqueBoxFlags, AVIF_UNIQUE_IDAT, "meta", "idat", diag), AVIF_RESULT_BMFF_PARSE_FAILED);
AVIF_CHECKERR(avifParseItemDataBox(meta, avifROStreamCurrent(&s), header.size, diag), AVIF_RESULT_BMFF_PARSE_FAILED);
} else if (!memcmp(header.type, "iprp", 4)) {
AVIF_CHECKERR(uniqueBoxSeen(&uniqueBoxFlags, AVIF_UNIQUE_IPRP, "meta", "iprp", diag), AVIF_RESULT_BMFF_PARSE_FAILED);
AVIF_CHECKRES(avifParseItemPropertiesBox(meta, rawOffset + avifROStreamOffset(&s), avifROStreamCurrent(&s), header.size, diag));
} else if (!memcmp(header.type, "iinf", 4)) {
AVIF_CHECKERR(uniqueBoxSeen(&uniqueBoxFlags, AVIF_UNIQUE_IINF, "meta", "iinf", diag), AVIF_RESULT_BMFF_PARSE_FAILED);
AVIF_CHECKRES(avifParseItemInfoBox(meta, avifROStreamCurrent(&s), header.size, diag));
} else if (!memcmp(header.type, "iref", 4)) {
AVIF_CHECKERR(uniqueBoxSeen(&uniqueBoxFlags, AVIF_UNIQUE_IREF, "meta", "iref", diag), AVIF_RESULT_BMFF_PARSE_FAILED);
AVIF_CHECKRES(avifParseItemReferenceBox(meta, avifROStreamCurrent(&s), header.size, diag));
} else if (!memcmp(header.type, "grpl", 4)) {
AVIF_CHECKERR(uniqueBoxSeen(&uniqueBoxFlags, AVIF_UNIQUE_GRPL, "meta", "grpl", diag), AVIF_RESULT_BMFF_PARSE_FAILED);
AVIF_CHECKRES(avifParseGroupsListBox(meta, avifROStreamCurrent(&s), header.size, diag));
}
AVIF_CHECKERR(avifROStreamSkip(&s, header.size), AVIF_RESULT_BMFF_PARSE_FAILED);
}
if (firstBox) {
// The meta box must not be empty (it must contain at least a hdlr box)
avifDiagnosticsPrintf(diag, "Box[meta] has no child boxes");
return AVIF_RESULT_BMFF_PARSE_FAILED;
}
return AVIF_RESULT_OK;
}
static avifBool avifParseTrackHeaderBox(avifTrack * track, const uint8_t * raw, size_t rawLen, avifDiagnostics * diag)
{
BEGIN_STREAM(s, raw, rawLen, diag, "Box[tkhd]");
uint8_t version;
AVIF_CHECK(avifROStreamReadVersionAndFlags(&s, &version, NULL));
uint32_t ignored32, trackID;
uint64_t ignored64;
if (version == 1) {
AVIF_CHECK(avifROStreamReadU64(&s, &ignored64)); // unsigned int(64) creation_time;
AVIF_CHECK(avifROStreamReadU64(&s, &ignored64)); // unsigned int(64) modification_time;
AVIF_CHECK(avifROStreamReadU32(&s, &trackID)); // unsigned int(32) track_ID;
AVIF_CHECK(avifROStreamReadU32(&s, &ignored32)); // const unsigned int(32) reserved = 0;
AVIF_CHECK(avifROStreamReadU64(&s, &track->trackDuration)); // unsigned int(64) duration;
} else if (version == 0) {
uint32_t trackDuration;
AVIF_CHECK(avifROStreamReadU32(&s, &ignored32)); // unsigned int(32) creation_time;
AVIF_CHECK(avifROStreamReadU32(&s, &ignored32)); // unsigned int(32) modification_time;
AVIF_CHECK(avifROStreamReadU32(&s, &trackID)); // unsigned int(32) track_ID;
AVIF_CHECK(avifROStreamReadU32(&s, &ignored32)); // const unsigned int(32) reserved = 0;
AVIF_CHECK(avifROStreamReadU32(&s, &trackDuration)); // unsigned int(32) duration;
track->trackDuration = (trackDuration == AVIF_INDEFINITE_DURATION32) ? AVIF_INDEFINITE_DURATION64 : trackDuration;
} else {
// Unsupported version
avifDiagnosticsPrintf(diag, "Box[tkhd] has an unsupported version [%u]", version);
return AVIF_FALSE;
}
track->id = trackID;
// Skipping the following 52 bytes here:
// ------------------------------------
// const unsigned int(32)[2] reserved = 0;
// template int(16) layer = 0;
// template int(16) alternate_group = 0;
// template int(16) volume = {if track_is_audio 0x0100 else 0};
// const unsigned int(16) reserved = 0;
// template int(32)[9] matrix= { 0x00010000,0,0,0,0x00010000,0,0,0,0x40000000 }; // unity matrix
AVIF_CHECK(avifROStreamSkip(&s, 52));
uint32_t width, height;
AVIF_CHECK(avifROStreamReadU32(&s, &width)); // unsigned int(32) width;
AVIF_CHECK(avifROStreamReadU32(&s, &height)); // unsigned int(32) height;
track->width = width >> 16;
track->height = height >> 16;
// TODO: support scaling based on width/height track header info?
return AVIF_TRUE;
}
static avifBool avifParseMediaHeaderBox(avifTrack * track, const uint8_t * raw, size_t rawLen, avifDiagnostics * diag)
{
BEGIN_STREAM(s, raw, rawLen, diag, "Box[mdhd]");
uint8_t version;
AVIF_CHECK(avifROStreamReadVersionAndFlags(&s, &version, NULL));
uint32_t ignored32, mediaTimescale, mediaDuration32;
uint64_t ignored64, mediaDuration64;
if (version == 1) {
AVIF_CHECK(avifROStreamReadU64(&s, &ignored64)); // unsigned int(64) creation_time;
AVIF_CHECK(avifROStreamReadU64(&s, &ignored64)); // unsigned int(64) modification_time;
AVIF_CHECK(avifROStreamReadU32(&s, &mediaTimescale)); // unsigned int(32) timescale;
AVIF_CHECK(avifROStreamReadU64(&s, &mediaDuration64)); // unsigned int(64) duration;
track->mediaDuration = mediaDuration64;
} else if (version == 0) {
AVIF_CHECK(avifROStreamReadU32(&s, &ignored32)); // unsigned int(32) creation_time;
AVIF_CHECK(avifROStreamReadU32(&s, &ignored32)); // unsigned int(32) modification_time;
AVIF_CHECK(avifROStreamReadU32(&s, &mediaTimescale)); // unsigned int(32) timescale;
AVIF_CHECK(avifROStreamReadU32(&s, &mediaDuration32)); // unsigned int(32) duration;
track->mediaDuration = (uint64_t)mediaDuration32;
} else {
// Unsupported version
avifDiagnosticsPrintf(diag, "Box[mdhd] has an unsupported version [%u]", version);
return AVIF_FALSE;
}
track->mediaTimescale = mediaTimescale;
return AVIF_TRUE;
}
static avifResult avifParseChunkOffsetBox(avifSampleTable * sampleTable, avifBool largeOffsets, const uint8_t * raw, size_t rawLen, avifDiagnostics * diag)
{
BEGIN_STREAM(s, raw, rawLen, diag, largeOffsets ? "Box[co64]" : "Box[stco]");
AVIF_CHECKERR(avifROStreamReadAndEnforceVersion(&s, /*enforcedVersion=*/0, /*flags=*/NULL), AVIF_RESULT_BMFF_PARSE_FAILED);
uint32_t entryCount;
AVIF_CHECKERR(avifROStreamReadU32(&s, &entryCount), AVIF_RESULT_BMFF_PARSE_FAILED); // unsigned int(32) entry_count;
for (uint32_t i = 0; i < entryCount; ++i) {
uint64_t offset;
if (largeOffsets) {
AVIF_CHECKERR(avifROStreamReadU64(&s, &offset), AVIF_RESULT_BMFF_PARSE_FAILED); // unsigned int(64) chunk_offset;
} else {
uint32_t offset32;
AVIF_CHECKERR(avifROStreamReadU32(&s, &offset32), AVIF_RESULT_BMFF_PARSE_FAILED); // unsigned int(32) chunk_offset;
offset = (uint64_t)offset32;
}
avifSampleTableChunk * chunk = (avifSampleTableChunk *)avifArrayPush(&sampleTable->chunks);
AVIF_CHECKERR(chunk != NULL, AVIF_RESULT_OUT_OF_MEMORY);
chunk->offset = offset;
}
return AVIF_RESULT_OK;
}
static avifResult avifParseSampleToChunkBox(avifSampleTable * sampleTable, const uint8_t * raw, size_t rawLen, avifDiagnostics * diag)
{
BEGIN_STREAM(s, raw, rawLen, diag, "Box[stsc]");
AVIF_CHECKERR(avifROStreamReadAndEnforceVersion(&s, /*enforcedVersion=*/0, /*flags=*/NULL), AVIF_RESULT_BMFF_PARSE_FAILED);
uint32_t entryCount;
AVIF_CHECKERR(avifROStreamReadU32(&s, &entryCount), AVIF_RESULT_BMFF_PARSE_FAILED); // unsigned int(32) entry_count;
uint32_t prevFirstChunk = 0;
for (uint32_t i = 0; i < entryCount; ++i) {
avifSampleTableSampleToChunk * sampleToChunk = (avifSampleTableSampleToChunk *)avifArrayPush(&sampleTable->sampleToChunks);
AVIF_CHECKERR(sampleToChunk != NULL, AVIF_RESULT_OUT_OF_MEMORY);
AVIF_CHECKERR(avifROStreamReadU32(&s, &sampleToChunk->firstChunk), AVIF_RESULT_BMFF_PARSE_FAILED); // unsigned int(32) first_chunk;
AVIF_CHECKERR(avifROStreamReadU32(&s, &sampleToChunk->samplesPerChunk), AVIF_RESULT_BMFF_PARSE_FAILED); // unsigned int(32) samples_per_chunk;
AVIF_CHECKERR(avifROStreamReadU32(&s, &sampleToChunk->sampleDescriptionIndex),
AVIF_RESULT_BMFF_PARSE_FAILED); // unsigned int(32) sample_description_index;
// The first_chunk fields should start with 1 and be strictly increasing.
if (i == 0) {
if (sampleToChunk->firstChunk != 1) {
avifDiagnosticsPrintf(diag, "Box[stsc] does not begin with chunk 1 [%u]", sampleToChunk->firstChunk);
return AVIF_RESULT_BMFF_PARSE_FAILED;
}
} else {
if (sampleToChunk->firstChunk <= prevFirstChunk) {
avifDiagnosticsPrintf(diag, "Box[stsc] chunks are not strictly increasing");
return AVIF_RESULT_BMFF_PARSE_FAILED;
}
}
prevFirstChunk = sampleToChunk->firstChunk;
}
return AVIF_RESULT_OK;
}
static avifResult avifParseSampleSizeBox(avifSampleTable * sampleTable, const uint8_t * raw, size_t rawLen, avifDiagnostics * diag)
{
BEGIN_STREAM(s, raw, rawLen, diag, "Box[stsz]");
AVIF_CHECKERR(avifROStreamReadAndEnforceVersion(&s, /*enforcedVersion=*/0, /*flags=*/NULL), AVIF_RESULT_BMFF_PARSE_FAILED);
uint32_t allSamplesSize, sampleCount;
AVIF_CHECKERR(avifROStreamReadU32(&s, &allSamplesSize), AVIF_RESULT_BMFF_PARSE_FAILED); // unsigned int(32) sample_size;
AVIF_CHECKERR(avifROStreamReadU32(&s, &sampleCount), AVIF_RESULT_BMFF_PARSE_FAILED); // unsigned int(32) sample_count;
if (allSamplesSize > 0) {
sampleTable->allSamplesSize = allSamplesSize;
} else {
for (uint32_t i = 0; i < sampleCount; ++i) {
avifSampleTableSampleSize * sampleSize = (avifSampleTableSampleSize *)avifArrayPush(&sampleTable->sampleSizes);
AVIF_CHECKERR(sampleSize != NULL, AVIF_RESULT_OUT_OF_MEMORY);
AVIF_CHECKERR(avifROStreamReadU32(&s, &sampleSize->size), AVIF_RESULT_BMFF_PARSE_FAILED); // unsigned int(32) entry_size;
}
}
return AVIF_RESULT_OK;
}
static avifResult avifParseSyncSampleBox(avifSampleTable * sampleTable, const uint8_t * raw, size_t rawLen, avifDiagnostics * diag)
{
BEGIN_STREAM(s, raw, rawLen, diag, "Box[stss]");
AVIF_CHECKERR(avifROStreamReadAndEnforceVersion(&s, /*enforcedVersion=*/0, /*flags=*/NULL), AVIF_RESULT_BMFF_PARSE_FAILED);
uint32_t entryCount;
AVIF_CHECKERR(avifROStreamReadU32(&s, &entryCount), AVIF_RESULT_BMFF_PARSE_FAILED); // unsigned int(32) entry_count;
for (uint32_t i = 0; i < entryCount; ++i) {
uint32_t sampleNumber = 0;
AVIF_CHECKERR(avifROStreamReadU32(&s, &sampleNumber), AVIF_RESULT_BMFF_PARSE_FAILED); // unsigned int(32) sample_number;
avifSyncSample * syncSample = (avifSyncSample *)avifArrayPush(&sampleTable->syncSamples);
AVIF_CHECKERR(syncSample != NULL, AVIF_RESULT_OUT_OF_MEMORY);
syncSample->sampleNumber = sampleNumber;
}
return AVIF_RESULT_OK;
}
static avifResult avifParseTimeToSampleBox(avifSampleTable * sampleTable, const uint8_t * raw, size_t rawLen, avifDiagnostics * diag)
{
BEGIN_STREAM(s, raw, rawLen, diag, "Box[stts]");
AVIF_CHECKERR(avifROStreamReadAndEnforceVersion(&s, /*enforcedVersion=*/0, /*flags=*/NULL), AVIF_RESULT_BMFF_PARSE_FAILED);
uint32_t entryCount;
AVIF_CHECKERR(avifROStreamReadU32(&s, &entryCount), AVIF_RESULT_BMFF_PARSE_FAILED); // unsigned int(32) entry_count;
for (uint32_t i = 0; i < entryCount; ++i) {
avifSampleTableTimeToSample * timeToSample = (avifSampleTableTimeToSample *)avifArrayPush(&sampleTable->timeToSamples);
AVIF_CHECKERR(timeToSample != NULL, AVIF_RESULT_OUT_OF_MEMORY);
AVIF_CHECKERR(avifROStreamReadU32(&s, &timeToSample->sampleCount), AVIF_RESULT_BMFF_PARSE_FAILED); // unsigned int(32) sample_count;
AVIF_CHECKERR(avifROStreamReadU32(&s, &timeToSample->sampleDelta), AVIF_RESULT_BMFF_PARSE_FAILED); // unsigned int(32) sample_delta;
}
return AVIF_RESULT_OK;
}
static avifResult avifParseSampleDescriptionBox(avifSampleTable * sampleTable,
uint64_t rawOffset,
const uint8_t * raw,
size_t rawLen,
avifDiagnostics * diag)
{
BEGIN_STREAM(s, raw, rawLen, diag, "Box[stsd]");
uint8_t version;
AVIF_CHECKERR(avifROStreamReadVersionAndFlags(&s, &version, NULL), AVIF_RESULT_BMFF_PARSE_FAILED);
// Section 8.5.2.3 of ISO/IEC 14496-12:
// version is set to zero. A version number of 1 shall be treated as a version of 0.
if (version != 0 && version != 1) {
avifDiagnosticsPrintf(diag, "Box[stsd]: Expecting box version 0 or 1, got version %u", version);
return AVIF_RESULT_BMFF_PARSE_FAILED;
}
uint32_t entryCount;
AVIF_CHECKERR(avifROStreamReadU32(&s, &entryCount), AVIF_RESULT_BMFF_PARSE_FAILED); // unsigned int(32) entry_count;
for (uint32_t i = 0; i < entryCount; ++i) {
avifBoxHeader sampleEntryHeader;
AVIF_CHECKERR(avifROStreamReadBoxHeader(&s, &sampleEntryHeader), AVIF_RESULT_BMFF_PARSE_FAILED);
avifSampleDescription * description = (avifSampleDescription *)avifArrayPush(&sampleTable->sampleDescriptions);
AVIF_CHECKERR(description != NULL, AVIF_RESULT_OUT_OF_MEMORY);
if (!avifArrayCreate(&description->properties, sizeof(avifProperty), 16)) {
avifArrayPop(&sampleTable->sampleDescriptions);
return AVIF_RESULT_OUT_OF_MEMORY;
}
memcpy(description->format, sampleEntryHeader.type, sizeof(description->format));
const size_t sampleEntryBytes = sampleEntryHeader.size;
if (avifGetCodecType(description->format) != AVIF_CODEC_TYPE_UNKNOWN) {
if (sampleEntryBytes < VISUALSAMPLEENTRY_SIZE) {
avifDiagnosticsPrintf(diag, "Not enough bytes to parse VisualSampleEntry");
return AVIF_RESULT_BMFF_PARSE_FAILED;
}
AVIF_CHECKRES(avifParseItemPropertyContainerBox(&description->properties,
rawOffset + avifROStreamOffset(&s) + VISUALSAMPLEENTRY_SIZE,
avifROStreamCurrent(&s) + VISUALSAMPLEENTRY_SIZE,
sampleEntryBytes - VISUALSAMPLEENTRY_SIZE,
/*isTrack=*/AVIF_TRUE,
diag));
}
AVIF_CHECKERR(avifROStreamSkip(&s, sampleEntryBytes), AVIF_RESULT_BMFF_PARSE_FAILED);
}
return AVIF_RESULT_OK;
}
static avifResult avifParseSampleTableBox(avifTrack * track, uint64_t rawOffset, const uint8_t * raw, size_t rawLen, avifDiagnostics * diag)
{
if (track->sampleTable) {
// A TrackBox may only have one SampleTable
avifDiagnosticsPrintf(diag, "Duplicate Box[stbl] for a single track detected");
return AVIF_RESULT_BMFF_PARSE_FAILED;
}
track->sampleTable = avifSampleTableCreate();
AVIF_CHECKERR(track->sampleTable != NULL, AVIF_RESULT_OUT_OF_MEMORY);
BEGIN_STREAM(s, raw, rawLen, diag, "Box[stbl]");
while (avifROStreamHasBytesLeft(&s, 1)) {
avifBoxHeader header;
AVIF_CHECKERR(avifROStreamReadBoxHeader(&s, &header), AVIF_RESULT_BMFF_PARSE_FAILED);
if (!memcmp(header.type, "stco", 4)) {
AVIF_CHECKRES(avifParseChunkOffsetBox(track->sampleTable, AVIF_FALSE, avifROStreamCurrent(&s), header.size, diag));
} else if (!memcmp(header.type, "co64", 4)) {
AVIF_CHECKRES(avifParseChunkOffsetBox(track->sampleTable, AVIF_TRUE, avifROStreamCurrent(&s), header.size, diag));
} else if (!memcmp(header.type, "stsc", 4)) {
AVIF_CHECKRES(avifParseSampleToChunkBox(track->sampleTable, avifROStreamCurrent(&s), header.size, diag));
} else if (!memcmp(header.type, "stsz", 4)) {
AVIF_CHECKRES(avifParseSampleSizeBox(track->sampleTable, avifROStreamCurrent(&s), header.size, diag));
} else if (!memcmp(header.type, "stss", 4)) {
AVIF_CHECKRES(avifParseSyncSampleBox(track->sampleTable, avifROStreamCurrent(&s), header.size, diag));
} else if (!memcmp(header.type, "stts", 4)) {
AVIF_CHECKRES(avifParseTimeToSampleBox(track->sampleTable, avifROStreamCurrent(&s), header.size, diag));
} else if (!memcmp(header.type, "stsd", 4)) {
AVIF_CHECKRES(avifParseSampleDescriptionBox(track->sampleTable,
rawOffset + avifROStreamOffset(&s),
avifROStreamCurrent(&s),
header.size,
diag));
}
AVIF_CHECKERR(avifROStreamSkip(&s, header.size), AVIF_RESULT_BMFF_PARSE_FAILED);
}
return AVIF_RESULT_OK;
}
static avifResult avifParseMediaInformationBox(avifTrack * track, uint64_t rawOffset, const uint8_t * raw, size_t rawLen, avifDiagnostics * diag)
{
BEGIN_STREAM(s, raw, rawLen, diag, "Box[minf]");
while (avifROStreamHasBytesLeft(&s, 1)) {
avifBoxHeader header;
AVIF_CHECKERR(avifROStreamReadBoxHeader(&s, &header), AVIF_RESULT_BMFF_PARSE_FAILED);
if (!memcmp(header.type, "stbl", 4)) {
AVIF_CHECKRES(avifParseSampleTableBox(track, rawOffset + avifROStreamOffset(&s), avifROStreamCurrent(&s), header.size, diag));
}
AVIF_CHECKERR(avifROStreamSkip(&s, header.size), AVIF_RESULT_BMFF_PARSE_FAILED);
}
return AVIF_RESULT_OK;
}
static avifResult avifParseMediaBox(avifTrack * track, uint64_t rawOffset, const uint8_t * raw, size_t rawLen, avifDiagnostics * diag)
{
BEGIN_STREAM(s, raw, rawLen, diag, "Box[mdia]");
while (avifROStreamHasBytesLeft(&s, 1)) {
avifBoxHeader header;
AVIF_CHECKERR(avifROStreamReadBoxHeader(&s, &header), AVIF_RESULT_BMFF_PARSE_FAILED);
if (!memcmp(header.type, "mdhd", 4)) {
AVIF_CHECKERR(avifParseMediaHeaderBox(track, avifROStreamCurrent(&s), header.size, diag), AVIF_RESULT_BMFF_PARSE_FAILED);
} else if (!memcmp(header.type, "minf", 4)) {
AVIF_CHECKRES(
avifParseMediaInformationBox(track, rawOffset + avifROStreamOffset(&s), avifROStreamCurrent(&s), header.size, diag));
} else if (!memcmp(header.type, "hdlr", 4)) {
AVIF_CHECKERR(avifParseHandlerBox(avifROStreamCurrent(&s), header.size, track->handlerType, diag),
AVIF_RESULT_BMFF_PARSE_FAILED);
}
AVIF_CHECKERR(avifROStreamSkip(&s, header.size), AVIF_RESULT_BMFF_PARSE_FAILED);
}
return AVIF_RESULT_OK;
}
static avifBool avifTrackReferenceBox(avifTrack * track, const uint8_t * raw, size_t rawLen, avifDiagnostics * diag)
{
BEGIN_STREAM(s, raw, rawLen, diag, "Box[tref]");
while (avifROStreamHasBytesLeft(&s, 1)) {
avifBoxHeader header;
AVIF_CHECK(avifROStreamReadBoxHeader(&s, &header));
if (!memcmp(header.type, "auxl", 4)) {
uint32_t toID;
AVIF_CHECK(avifROStreamReadU32(&s, &toID)); // unsigned int(32) track_IDs[];
AVIF_CHECK(avifROStreamSkip(&s, header.size - sizeof(uint32_t))); // just take the first one
track->auxForID = toID;
} else if (!memcmp(header.type, "prem", 4)) {
uint32_t byID;
AVIF_CHECK(avifROStreamReadU32(&s, &byID)); // unsigned int(32) track_IDs[];
AVIF_CHECK(avifROStreamSkip(&s, header.size - sizeof(uint32_t))); // just take the first one
track->premByID = byID;
} else {
AVIF_CHECK(avifROStreamSkip(&s, header.size));
}
}
return AVIF_TRUE;
}
static avifBool avifParseEditListBox(avifTrack * track, const uint8_t * raw, size_t rawLen, avifDiagnostics * diag)
{
BEGIN_STREAM(s, raw, rawLen, diag, "Box[elst]");
uint8_t version;
uint32_t flags;
AVIF_CHECK(avifROStreamReadVersionAndFlags(&s, &version, &flags));
if ((flags & 1) == 0) {
track->isRepeating = AVIF_FALSE;
return AVIF_TRUE;
}
track->isRepeating = AVIF_TRUE;
uint32_t entryCount;
AVIF_CHECK(avifROStreamReadU32(&s, &entryCount)); // unsigned int(32) entry_count;
if (entryCount != 1) {
avifDiagnosticsPrintf(diag, "Box[elst] contains an entry_count != 1 [%u]", entryCount);
return AVIF_FALSE;
}
if (version == 1) {
AVIF_CHECK(avifROStreamReadU64(&s, &track->segmentDuration)); // unsigned int(64) segment_duration;
} else if (version == 0) {
uint32_t segmentDuration;
AVIF_CHECK(avifROStreamReadU32(&s, &segmentDuration)); // unsigned int(32) segment_duration;
track->segmentDuration = segmentDuration;
} else {
// Unsupported version
avifDiagnosticsPrintf(diag, "Box[elst] has an unsupported version [%u]", version);
return AVIF_FALSE;
}
if (track->segmentDuration == 0) {
avifDiagnosticsPrintf(diag, "Box[elst] Invalid value for segment_duration (0).");
return AVIF_FALSE;
}
return AVIF_TRUE;
}
static avifBool avifParseEditBox(avifTrack * track, const uint8_t * raw, size_t rawLen, avifDiagnostics * diag)
{
BEGIN_STREAM(s, raw, rawLen, diag, "Box[edts]");
avifBool elstBoxSeen = AVIF_FALSE;
while (avifROStreamHasBytesLeft(&s, 1)) {
avifBoxHeader header;
AVIF_CHECK(avifROStreamReadBoxHeader(&s, &header));
if (!memcmp(header.type, "elst", 4)) {
if (elstBoxSeen) {
avifDiagnosticsPrintf(diag, "More than one [elst] Box was found.");
return AVIF_FALSE;
}
AVIF_CHECK(avifParseEditListBox(track, avifROStreamCurrent(&s), header.size, diag));
elstBoxSeen = AVIF_TRUE;
}
AVIF_CHECK(avifROStreamSkip(&s, header.size));
}
if (!elstBoxSeen) {
avifDiagnosticsPrintf(diag, "Box[edts] contains no [elst] Box.");
return AVIF_FALSE;
}
return AVIF_TRUE;
}
static avifResult avifParseTrackBox(avifDecoderData * data, uint64_t rawOffset, const uint8_t * raw, size_t rawLen)
{
BEGIN_STREAM(s, raw, rawLen, data->diag, "Box[trak]");
avifTrack * track = avifDecoderDataCreateTrack(data);
AVIF_CHECKERR(track != NULL, AVIF_RESULT_OUT_OF_MEMORY);
avifBool edtsBoxSeen = AVIF_FALSE;
avifBool tkhdSeen = AVIF_FALSE;
while (avifROStreamHasBytesLeft(&s, 1)) {
avifBoxHeader header;
AVIF_CHECKERR(avifROStreamReadBoxHeader(&s, &header), AVIF_RESULT_BMFF_PARSE_FAILED);
if (!memcmp(header.type, "tkhd", 4)) {
if (tkhdSeen) {
avifDiagnosticsPrintf(data->diag, "Box[trak] contains a duplicate unique box of type 'tkhd'");
return AVIF_RESULT_BMFF_PARSE_FAILED;
}
AVIF_CHECKERR(avifParseTrackHeaderBox(track, avifROStreamCurrent(&s), header.size, data->diag), AVIF_RESULT_BMFF_PARSE_FAILED);
tkhdSeen = AVIF_TRUE;
} else if (!memcmp(header.type, "meta", 4)) {
AVIF_CHECKRES(
avifParseMetaBox(track->meta, rawOffset + avifROStreamOffset(&s), avifROStreamCurrent(&s), header.size, data->diag));
} else if (!memcmp(header.type, "mdia", 4)) {
AVIF_CHECKRES(avifParseMediaBox(track, rawOffset + avifROStreamOffset(&s), avifROStreamCurrent(&s), header.size, data->diag));
} else if (!memcmp(header.type, "tref", 4)) {
AVIF_CHECKERR(avifTrackReferenceBox(track, avifROStreamCurrent(&s), header.size, data->diag), AVIF_RESULT_BMFF_PARSE_FAILED);
} else if (!memcmp(header.type, "edts", 4)) {
if (edtsBoxSeen) {
avifDiagnosticsPrintf(data->diag, "Box[trak] contains a duplicate unique box of type 'edts'");
return AVIF_RESULT_BMFF_PARSE_FAILED;
}
AVIF_CHECKERR(avifParseEditBox(track, avifROStreamCurrent(&s), header.size, data->diag), AVIF_RESULT_BMFF_PARSE_FAILED);
edtsBoxSeen = AVIF_TRUE;
}
AVIF_CHECKERR(avifROStreamSkip(&s, header.size), AVIF_RESULT_BMFF_PARSE_FAILED);
}
if (!tkhdSeen) {
avifDiagnosticsPrintf(data->diag, "Box[trak] does not contain a mandatory [tkhd] box");
return AVIF_RESULT_BMFF_PARSE_FAILED;
}
if (!edtsBoxSeen) {
track->repetitionCount = AVIF_REPETITION_COUNT_UNKNOWN;
} else if (track->isRepeating) {
if (track->trackDuration == AVIF_INDEFINITE_DURATION64) {
// If isRepeating is true and the track duration is unknown/indefinite, then set the repetition count to infinite
// (Section 9.6.1 of ISO/IEC 23008-12 Part 12).
track->repetitionCount = AVIF_REPETITION_COUNT_INFINITE;
} else {
// Section 9.6.1. of ISO/IEC 23008-12 Part 12: 1, the entire edit list is repeated a sufficient number of times to
// equal the track duration.
//
// Since libavif uses repetitionCount (which is 0-based), we subtract the value by 1 to derive the number of
// repetitions.
AVIF_ASSERT_OR_RETURN(track->segmentDuration != 0);
// We specifically check for trackDuration == 0 here and not when it is actually read in order to accept files which
// inadvertently has a trackDuration of 0 without any edit lists.
if (track->trackDuration == 0) {
avifDiagnosticsPrintf(data->diag, "Invalid track duration 0.");
return AVIF_RESULT_BMFF_PARSE_FAILED;
}
const uint64_t repetitionCount =
(track->trackDuration / track->segmentDuration) + (track->trackDuration % track->segmentDuration != 0) - 1;
if (repetitionCount > INT_MAX) {
// repetitionCount does not fit in an integer and hence it is
// likely to be a very large value. So, we just set it to
// infinite.
track->repetitionCount = AVIF_REPETITION_COUNT_INFINITE;
} else {
track->repetitionCount = (int)repetitionCount;
}
}
} else {
track->repetitionCount = 0;
}
return AVIF_RESULT_OK;
}
static avifResult avifParseMovieBox(avifDecoderData * data,
uint64_t rawOffset,
const uint8_t * raw,
size_t rawLen,
uint32_t imageSizeLimit,
uint32_t imageDimensionLimit)
{
BEGIN_STREAM(s, raw, rawLen, data->diag, "Box[moov]");
avifBool hasTrak = AVIF_FALSE;
while (avifROStreamHasBytesLeft(&s, 1)) {
avifBoxHeader header;
AVIF_CHECKERR(avifROStreamReadBoxHeader(&s, &header), AVIF_RESULT_BMFF_PARSE_FAILED);
if (!memcmp(header.type, "trak", 4)) {
AVIF_CHECKRES(avifParseTrackBox(data, rawOffset + avifROStreamOffset(&s), avifROStreamCurrent(&s), header.size));
hasTrak = AVIF_TRUE;
const avifTrack * track = &data->tracks.track[data->tracks.count - 1];
if (!memcmp(track->handlerType, "pict", 4) || !memcmp(track->handlerType, "vide", 4) ||
!memcmp(track->handlerType, "auxv", 4)) {
if ((track->width == 0) || (track->height == 0)) {
avifDiagnosticsPrintf(data->diag, "Track ID [%u] has an invalid size [%ux%u]", track->id, track->width, track->height);
return AVIF_RESULT_BMFF_PARSE_FAILED;
}
if (avifDimensionsTooLarge(track->width, track->height, imageSizeLimit, imageDimensionLimit)) {
avifDiagnosticsPrintf(data->diag,
"Track ID [%u] dimensions are too large [%ux%u]",
track->id,
track->width,
track->height);
return AVIF_RESULT_BMFF_PARSE_FAILED;
}
}
}
AVIF_CHECKERR(avifROStreamSkip(&s, header.size), AVIF_RESULT_BMFF_PARSE_FAILED);
}
if (!hasTrak) {
avifDiagnosticsPrintf(data->diag, "moov box does not contain any tracks");
return AVIF_RESULT_BMFF_PARSE_FAILED;
}
return AVIF_RESULT_OK;
}
#if defined(AVIF_ENABLE_EXPERIMENTAL_MINI)
static avifProperty * avifMetaCreateProperty(avifMeta * meta, const char * propertyType)
{
avifProperty * metaProperty = avifArrayPush(&meta->properties);
AVIF_CHECKERR(metaProperty, NULL);
memcpy(metaProperty->type, propertyType, 4);
return metaProperty;
}
static avifProperty * avifDecoderItemAddProperty(avifDecoderItem * item, const avifProperty * metaProperty)
{
avifProperty * itemProperty = avifArrayPush(&item->properties);
AVIF_CHECKERR(itemProperty, NULL);
*itemProperty = *metaProperty;
return itemProperty;
}
static avifResult avifParseMinimizedImageBox(avifDecoderData * data,
uint64_t rawOffset,
const uint8_t * raw,
size_t rawLen,
avifBool isAvifAccordingToMinorVersion,
avifDiagnostics * diag)
{
avifMeta * meta = data->meta;
BEGIN_STREAM(s, raw, rawLen, diag, "Box[mini]");
meta->fromMiniBox = AVIF_TRUE;
uint32_t version;
AVIF_CHECKERR(avifROStreamReadBitsU32(&s, &version, 2), AVIF_RESULT_BMFF_PARSE_FAILED); // bit(2) version = 0;
AVIF_CHECKERR(version == 0, AVIF_RESULT_BMFF_PARSE_FAILED);
// flags
uint32_t hasExplicitCodecTypes, floatFlag, fullRange, hasAlpha, hasExplicitCicp, hasHdr, hasIcc, hasExif, hasXmp;
AVIF_CHECKERR(avifROStreamReadBitsU32(&s, &hasExplicitCodecTypes, 1), AVIF_RESULT_BMFF_PARSE_FAILED); // bit(1) explicit_codec_types_flag;
AVIF_CHECKERR(avifROStreamReadBitsU32(&s, &floatFlag, 1), AVIF_RESULT_BMFF_PARSE_FAILED); // bit(1) float_flag;
AVIF_CHECKERR(avifROStreamReadBitsU32(&s, &fullRange, 1), AVIF_RESULT_BMFF_PARSE_FAILED); // bit(1) full_range_flag;
AVIF_CHECKERR(avifROStreamReadBitsU32(&s, &hasAlpha, 1), AVIF_RESULT_BMFF_PARSE_FAILED); // bit(1) alpha_flag;
AVIF_CHECKERR(avifROStreamReadBitsU32(&s, &hasExplicitCicp, 1), AVIF_RESULT_BMFF_PARSE_FAILED); // bit(1) explicit_cicp_flag;
AVIF_CHECKERR(avifROStreamReadBitsU32(&s, &hasHdr, 1), AVIF_RESULT_BMFF_PARSE_FAILED); // bit(1) hdr_flag;
AVIF_CHECKERR(avifROStreamReadBitsU32(&s, &hasIcc, 1), AVIF_RESULT_BMFF_PARSE_FAILED); // bit(1) icc_flag;
AVIF_CHECKERR(avifROStreamReadBitsU32(&s, &hasExif, 1), AVIF_RESULT_BMFF_PARSE_FAILED); // bit(1) exif_flag;
AVIF_CHECKERR(avifROStreamReadBitsU32(&s, &hasXmp, 1), AVIF_RESULT_BMFF_PARSE_FAILED); // bit(1) xmp_flag;
uint32_t chromaSubsampling, orientation;
AVIF_CHECKERR(avifROStreamReadBitsU32(&s, &chromaSubsampling, 2), AVIF_RESULT_BMFF_PARSE_FAILED); // bit(2) chroma_subsampling;
AVIF_CHECKERR(avifROStreamReadBitsU32(&s, &orientation, 3), AVIF_RESULT_BMFF_PARSE_FAILED); // bit(3) orientation_minus1;
++orientation;
// Spatial extents
uint32_t largeDimensionsFlag, width, height;
AVIF_CHECKERR(avifROStreamReadBitsU32(&s, &largeDimensionsFlag, 1), AVIF_RESULT_BMFF_PARSE_FAILED); // bit(1) large_dimensions_flag;
AVIF_CHECKERR(avifROStreamReadBitsU32(&s, &width, largeDimensionsFlag ? 15 : 7),
AVIF_RESULT_BMFF_PARSE_FAILED); // unsigned int(large_dimensions_flag ? 15 : 7) width_minus1;
++width;
AVIF_CHECKERR(avifROStreamReadBitsU32(&s, &height, largeDimensionsFlag ? 15 : 7),
AVIF_RESULT_BMFF_PARSE_FAILED); // unsigned int(large_dimensions_flag ? 15 : 7) height_minus1;
++height;
// Pixel information
uint32_t chromaIsHorizontallyCentered = 0, chromaIsVerticallyCentered = 0;
if (chromaSubsampling == 1 || chromaSubsampling == 2) {
AVIF_CHECKERR(avifROStreamReadBitsU32(&s, &chromaIsHorizontallyCentered, 1),
AVIF_RESULT_BMFF_PARSE_FAILED); // bit(1) chroma_is_horizontally_centered;
}
if (chromaSubsampling == 1) {
AVIF_CHECKERR(avifROStreamReadBitsU32(&s, &chromaIsVerticallyCentered, 1), AVIF_RESULT_BMFF_PARSE_FAILED); // bit(1) chroma_is_vertically_centered;
}
uint32_t bitDepth;
if (floatFlag) {
// bit(2) bit_depth_log2_minus4;
return AVIF_RESULT_BMFF_PARSE_FAILED; // Either invalid AVIF or unsupported non-AVIF.
} else {
uint32_t highBitDepthFlag;
AVIF_CHECKERR(avifROStreamReadBitsU32(&s, &highBitDepthFlag, 1), AVIF_RESULT_BMFF_PARSE_FAILED); // bit(1) high_bit_depth_flag;
if (highBitDepthFlag) {
AVIF_CHECKERR(avifROStreamReadBitsU32(&s, &bitDepth, 3), AVIF_RESULT_BMFF_PARSE_FAILED); // bit(3) bit_depth_minus9;
bitDepth += 9;
} else {
bitDepth = 8;
}
}
uint32_t alphaIsPremultiplied = 0;
if (hasAlpha) {
AVIF_CHECKERR(avifROStreamReadBitsU32(&s, &alphaIsPremultiplied, 1), AVIF_RESULT_BMFF_PARSE_FAILED); // bit(1) alpha_is_premultiplied;
}
// Colour properties
uint8_t colorPrimaries;
uint8_t transferCharacteristics;
uint8_t matrixCoefficients;
if (hasExplicitCicp) {
AVIF_CHECKERR(avifROStreamReadBitsU8(&s, &colorPrimaries, 8), AVIF_RESULT_BMFF_PARSE_FAILED); // bit(8) colour_primaries;
AVIF_CHECKERR(avifROStreamReadBitsU8(&s, &transferCharacteristics, 8), AVIF_RESULT_BMFF_PARSE_FAILED); // bit(8) transfer_characteristics;
if (chromaSubsampling != 0) {
AVIF_CHECKERR(avifROStreamReadBitsU8(&s, &matrixCoefficients, 8), AVIF_RESULT_BMFF_PARSE_FAILED); // bit(8) matrix_coefficients;
} else {
matrixCoefficients = AVIF_MATRIX_COEFFICIENTS_UNSPECIFIED; // 2
}
} else {
colorPrimaries = hasIcc ? AVIF_COLOR_PRIMARIES_UNSPECIFIED // 2
: AVIF_COLOR_PRIMARIES_BT709; // 1
transferCharacteristics = hasIcc ? AVIF_TRANSFER_CHARACTERISTICS_UNSPECIFIED // 2
: AVIF_TRANSFER_CHARACTERISTICS_SRGB; // 13
matrixCoefficients = chromaSubsampling == 0 ? AVIF_MATRIX_COEFFICIENTS_UNSPECIFIED // 2
: AVIF_MATRIX_COEFFICIENTS_BT601; // 6
}
uint8_t infeType[4];
uint8_t codecConfigType[4];
if (hasExplicitCodecTypes) {
// bit(32) infe_type;
for (int i = 0; i < 4; ++i) {
AVIF_CHECKERR(avifROStreamReadBitsU8(&s, &infeType[i], 8), AVIF_RESULT_BMFF_PARSE_FAILED);
}
// bit(32) codec_config_type;
for (int i = 0; i < 4; ++i) {
AVIF_CHECKERR(avifROStreamReadBitsU8(&s, &codecConfigType[i], 8), AVIF_RESULT_BMFF_PARSE_FAILED);
}
#if defined(AVIF_CODEC_AVM)
AVIF_CHECKERR((!memcmp(infeType, "av01", 4) && !memcmp(codecConfigType, "av1C", 4)) ||
(!memcmp(infeType, "av02", 4) && !memcmp(codecConfigType, "av2C", 4)),
AVIF_RESULT_BMFF_PARSE_FAILED);
#else
AVIF_CHECKERR(!memcmp(infeType, "av01", 4) && !memcmp(codecConfigType, "av1C", 4), AVIF_RESULT_BMFF_PARSE_FAILED);
#endif
} else {
AVIF_CHECKERR(isAvifAccordingToMinorVersion, AVIF_RESULT_BMFF_PARSE_FAILED);
memcpy(infeType, "av01", 4);
memcpy(codecConfigType, "av1C", 4);
}
// High Dynamic Range properties
uint32_t hasGainmap = AVIF_FALSE;
uint32_t tmapHasIcc = AVIF_FALSE;
uint32_t gainmapWidth = 0, gainmapHeight = 0;
uint8_t gainmapMatrixCoefficients = 0;
uint32_t gainmapFullRange = 0;
uint32_t gainmapChromaSubsampling = 0;
uint32_t gainmapBitDepth = 0;
uint32_t tmapHasExplicitCicp = AVIF_FALSE;
uint8_t tmapColorPrimaries = AVIF_COLOR_PRIMARIES_UNKNOWN;
uint8_t tmapTransferCharacteristics = AVIF_TRANSFER_CHARACTERISTICS_UNKNOWN;
uint8_t tmapMatrixCoefficients = AVIF_MATRIX_COEFFICIENTS_IDENTITY;
uint32_t tmapFullRange = AVIF_FALSE;
uint32_t hasClli = AVIF_FALSE, tmapHasClli = AVIF_FALSE;
avifContentLightLevelInformationBox clli = { 0 }, tmapClli = { 0 };
if (hasHdr) {
AVIF_CHECKERR(avifROStreamReadBitsU32(&s, &hasGainmap, 1), AVIF_RESULT_BMFF_PARSE_FAILED); // bit(1) gainmap_flag;
if (hasGainmap) {
// avifDecoderReset() requires the 'tmap' brand to be registered for the tone mapping derived image item to be parsed.
if (data->compatibleBrands.capacity == 0) {
AVIF_CHECKERR(avifArrayCreate(&data->compatibleBrands, sizeof(avifBrand), 1), AVIF_RESULT_OUT_OF_MEMORY);
}
avifBrand * brand = avifArrayPush(&data->compatibleBrands);
AVIF_CHECKERR(brand != NULL, AVIF_RESULT_OUT_OF_MEMORY);
memcpy(brand, "tmap", sizeof(avifBrand));
AVIF_CHECKERR(avifROStreamReadBitsU32(&s, &gainmapWidth, largeDimensionsFlag ? 15 : 7),
AVIF_RESULT_BMFF_PARSE_FAILED); // unsigned int(large_dimensions_flag ? 15 : 7) gainmap_width_minus1;
++gainmapWidth;
AVIF_CHECKERR(avifROStreamReadBitsU32(&s, &gainmapHeight, largeDimensionsFlag ? 15 : 7),
AVIF_RESULT_BMFF_PARSE_FAILED); // unsigned int(large_dimensions_flag ? 15 : 7) gainmap_height_minus1;
++gainmapHeight;
AVIF_CHECKERR(avifROStreamReadBitsU8(&s, &gainmapMatrixCoefficients, 8), AVIF_RESULT_BMFF_PARSE_FAILED); // bit(8) gainmap_matrix_coefficients;
AVIF_CHECKERR(avifROStreamReadBitsU32(&s, &gainmapFullRange, 1), AVIF_RESULT_BMFF_PARSE_FAILED); // bit(1) gainmap_full_range_flag;
AVIF_CHECKERR(avifROStreamReadBitsU32(&s, &gainmapChromaSubsampling, 2), AVIF_RESULT_BMFF_PARSE_FAILED); // bit(2) gainmap_chroma_subsampling;
uint32_t gainmapChromaIsHorizontallyCentered = 0, gainmapChromaIsVerticallyCentered = 0;
if (gainmapChromaSubsampling == 1 || gainmapChromaSubsampling == 2) {
AVIF_CHECKERR(avifROStreamReadBitsU32(&s, &gainmapChromaIsHorizontallyCentered, 1),
AVIF_RESULT_BMFF_PARSE_FAILED); // bit(1) gainmap_chroma_is_horizontally_centered;
}
if (gainmapChromaSubsampling == 1) {
AVIF_CHECKERR(avifROStreamReadBitsU32(&s, &gainmapChromaIsVerticallyCentered, 1),
AVIF_RESULT_BMFF_PARSE_FAILED); // bit(1) gainmap_chroma_is_vertically_centered;
}
uint32_t gainmapFloatFlag;
AVIF_CHECKERR(avifROStreamReadBitsU32(&s, &gainmapFloatFlag, 1), AVIF_RESULT_BMFF_PARSE_FAILED); // bit(1) gainmap_float_flag;
if (gainmapFloatFlag) {
// bit(2) gainmap_bit_depth_log2_minus4;
return AVIF_RESULT_BMFF_PARSE_FAILED; // Either invalid AVIF or unsupported non-AVIF.
} else {
uint32_t gainmapHighBitDepthFlag;
AVIF_CHECKERR(avifROStreamReadBitsU32(&s, &gainmapHighBitDepthFlag, 1), AVIF_RESULT_BMFF_PARSE_FAILED); // bit(1) gainmap_high_bit_depth_flag;
if (gainmapHighBitDepthFlag) {
AVIF_CHECKERR(avifROStreamReadBitsU32(&s, &gainmapBitDepth, 3), AVIF_RESULT_BMFF_PARSE_FAILED); // bit(3) gainmap_bit_depth_minus9;
gainmapBitDepth += 9;
} else {
gainmapBitDepth = 8;
}
}
AVIF_CHECKERR(avifROStreamReadBitsU32(&s, &tmapHasIcc, 1), AVIF_RESULT_BMFF_PARSE_FAILED); // bit(1) tmap_icc_flag;
AVIF_CHECKERR(avifROStreamReadBitsU32(&s, &tmapHasExplicitCicp, 1), AVIF_RESULT_BMFF_PARSE_FAILED); // bit(1) tmap_explicit_cicp_flag;
if (tmapHasExplicitCicp) {
AVIF_CHECKERR(avifROStreamReadBitsU8(&s, &tmapColorPrimaries, 8), AVIF_RESULT_BMFF_PARSE_FAILED); // bit(8) tmap_colour_primaries;
AVIF_CHECKERR(avifROStreamReadBitsU8(&s, &tmapTransferCharacteristics, 8),
AVIF_RESULT_BMFF_PARSE_FAILED); // bit(8) tmap_transfer_characteristics;
AVIF_CHECKERR(avifROStreamReadBitsU8(&s, &tmapMatrixCoefficients, 8), AVIF_RESULT_BMFF_PARSE_FAILED); // bit(8) tmap_matrix_coefficients;
AVIF_CHECKERR(avifROStreamReadBitsU32(&s, &tmapFullRange, 1), AVIF_RESULT_BMFF_PARSE_FAILED); // bit(1) tmap_full_range_flag;
} else {
tmapColorPrimaries = AVIF_COLOR_PRIMARIES_BT709; // 1
tmapTransferCharacteristics = AVIF_TRANSFER_CHARACTERISTICS_SRGB; // 13
tmapMatrixCoefficients = AVIF_MATRIX_COEFFICIENTS_BT601; // 6
tmapFullRange = 1;
}
}
AVIF_CHECKRES(avifParseMiniHDRProperties(&s, &hasClli, &clli));
if (hasGainmap) {
AVIF_CHECKRES(avifParseMiniHDRProperties(&s, &tmapHasClli, &tmapClli));
}
}
// Chunk sizes
uint32_t largeMetadataFlag = 0, largeCodecConfigFlag = 0, largeItemDataFlag = 0;
if (hasIcc || hasExif || hasXmp || (hasHdr && hasGainmap)) {
AVIF_CHECKERR(avifROStreamReadBitsU32(&s, &largeMetadataFlag, 1), AVIF_RESULT_BMFF_PARSE_FAILED); // bit(1) large_metadata_flag;
}
AVIF_CHECKERR(avifROStreamReadBitsU32(&s, &largeCodecConfigFlag, 1), AVIF_RESULT_BMFF_PARSE_FAILED); // bit(1) large_codec_config_flag;
AVIF_CHECKERR(avifROStreamReadBitsU32(&s, &largeItemDataFlag, 1), AVIF_RESULT_BMFF_PARSE_FAILED); // bit(1) large_item_data_flag;
uint32_t iccDataSize = 0;
if (hasIcc) {
AVIF_CHECKERR(avifROStreamReadBitsU32(&s, &iccDataSize, largeMetadataFlag ? 20 : 10),
AVIF_RESULT_BMFF_PARSE_FAILED); // unsigned int(large_metadata_flag ? 20 : 10) icc_data_size_minus1;
++iccDataSize;
}
uint32_t tmapIccDataSize = 0;
if (hasHdr && hasGainmap && tmapHasIcc) {
AVIF_CHECKERR(avifROStreamReadBitsU32(&s, &tmapIccDataSize, largeMetadataFlag ? 20 : 10),
AVIF_RESULT_BMFF_PARSE_FAILED); // unsigned int(large_metadata_flag ? 20 : 10) tmap_icc_data_size_minus1;
++tmapIccDataSize;
}
uint32_t gainmapMetadataSize = 0, gainmapItemDataSize = 0, gainmapItemCodecConfigSize = 0;
if (hasHdr && hasGainmap) {
AVIF_CHECKERR(avifROStreamReadBitsU32(&s, &gainmapMetadataSize, largeMetadataFlag ? 20 : 10),
AVIF_RESULT_BMFF_PARSE_FAILED); // unsigned int(large_metadata_flag ? 20 : 10) gainmap_metadata_size;
AVIF_CHECKERR(avifROStreamReadBitsU32(&s, &gainmapItemDataSize, largeItemDataFlag ? 28 : 15),
AVIF_RESULT_BMFF_PARSE_FAILED); // unsigned int(large_item_data_flag ? 28 : 15) gainmap_item_data_size;
if (gainmapItemDataSize != 0) {
AVIF_CHECKERR(avifROStreamReadBitsU32(&s, &gainmapItemCodecConfigSize, largeCodecConfigFlag ? 12 : 3),
AVIF_RESULT_BMFF_PARSE_FAILED); // unsigned int(large_codec_config_flag ? 12 : 3) gainmap_item_codec_config_size;
}
}
uint32_t mainItemCodecConfigSize, mainItemDataSize;
AVIF_CHECKERR(avifROStreamReadBitsU32(&s, &mainItemCodecConfigSize, largeCodecConfigFlag ? 12 : 3),
AVIF_RESULT_BMFF_PARSE_FAILED); // unsigned int(large_codec_config_flag ? 12 : 3) main_item_codec_config_size;
AVIF_CHECKERR(avifROStreamReadBitsU32(&s, &mainItemDataSize, largeItemDataFlag ? 28 : 15),
AVIF_RESULT_BMFF_PARSE_FAILED); // unsigned int(large_item_data_flag ? 28 : 15) main_item_data_size_minus1;
++mainItemDataSize;
uint32_t alphaItemCodecConfigSize = 0, alphaItemDataSize = 0;
if (hasAlpha) {
AVIF_CHECKERR(avifROStreamReadBitsU32(&s, &alphaItemDataSize, largeItemDataFlag ? 28 : 15),
AVIF_RESULT_BMFF_PARSE_FAILED); // unsigned int(large_item_data_flag ? 28 : 15) alpha_item_data_size;
}
if (hasAlpha && alphaItemDataSize != 0) {
AVIF_CHECKERR(avifROStreamReadBitsU32(&s, &alphaItemCodecConfigSize, largeCodecConfigFlag ? 12 : 3),
AVIF_RESULT_BMFF_PARSE_FAILED); // unsigned int(large_codec_config_flag ? 12 : 3) alpha_item_codec_config_size;
}
if (hasExif || hasXmp) {
uint8_t exifXmpCompressedFlag;
AVIF_CHECKERR(avifROStreamReadBitsU8(&s, &exifXmpCompressedFlag, 1),
AVIF_RESULT_BMFF_PARSE_FAILED); // unsigned int(1) exif_xmp_compressed_flag;
AVIF_CHECKERR(!exifXmpCompressedFlag, AVIF_RESULT_NOT_IMPLEMENTED);
}
uint32_t exifDataSize = 0;
if (hasExif) {
AVIF_CHECKERR(avifROStreamReadBitsU32(&s, &exifDataSize, largeMetadataFlag ? 20 : 10),
AVIF_RESULT_BMFF_PARSE_FAILED); // unsigned int(large_metadata_flag ? 20 : 10) exif_data_size_minus_one;
++exifDataSize;
}
uint32_t xmpDataSize = 0;
if (hasXmp) {
AVIF_CHECKERR(avifROStreamReadBitsU32(&s, &xmpDataSize, largeMetadataFlag ? 20 : 10),
AVIF_RESULT_BMFF_PARSE_FAILED); // unsigned int(large_metadata_flag ? 20 : 10) xmp_data_size_minus_one;
++xmpDataSize;
}
// trailing_bits(); // bit padding till byte alignment
if (s.numUsedBitsInPartialByte) {
uint32_t padding;
AVIF_CHECKERR(avifROStreamReadBitsU32(&s, &padding, 8 - s.numUsedBitsInPartialByte), AVIF_RESULT_BMFF_PARSE_FAILED);
AVIF_CHECKERR(padding == 0, AVIF_RESULT_BMFF_PARSE_FAILED); // Only accept zeros as padding.
}
// Codec configuration ('av1C' always uses 4 bytes)
avifCodecConfigurationBox mainItemCodecConfig;
AVIF_CHECKERR(mainItemCodecConfigSize == 4, AVIF_RESULT_BMFF_PARSE_FAILED);
AVIF_CHECKERR(avifParseCodecConfiguration(&s, &mainItemCodecConfig, (const char *)codecConfigType, diag),
AVIF_RESULT_BMFF_PARSE_FAILED); // unsigned int(8) main_item_codec_config[main_item_codec_config_size];
avifCodecConfigurationBox alphaItemCodecConfig = { 0 };
if (hasAlpha && alphaItemDataSize != 0) {
if (alphaItemCodecConfigSize == 0) {
alphaItemCodecConfigSize = mainItemCodecConfigSize;
alphaItemCodecConfig = mainItemCodecConfig;
} else {
AVIF_CHECKERR(alphaItemCodecConfigSize == 4, AVIF_RESULT_BMFF_PARSE_FAILED);
AVIF_CHECKERR(avifParseCodecConfiguration(&s, &alphaItemCodecConfig, (const char *)codecConfigType, diag),
AVIF_RESULT_BMFF_PARSE_FAILED); // unsigned int(8) alpha_item_codec_config[alpha_item_codec_config_size];
}
}
avifCodecConfigurationBox gainmapItemCodecConfig = { 0 };
if (hasHdr && hasGainmap && gainmapItemDataSize != 0) {
if (gainmapItemCodecConfigSize == 0) {
gainmapItemCodecConfigSize = mainItemCodecConfigSize;
gainmapItemCodecConfig = mainItemCodecConfig;
} else {
AVIF_CHECKERR(gainmapItemCodecConfigSize == 4, AVIF_RESULT_BMFF_PARSE_FAILED);
AVIF_CHECKERR(avifParseCodecConfiguration(&s, &gainmapItemCodecConfig, (const char *)codecConfigType, diag),
AVIF_RESULT_BMFF_PARSE_FAILED); // unsigned int(8) gainmap_item_codec_config[gainmap_item_codec_config_size];
}
}
// Make sure all metadata and coded chunks fit into the 'meta' box whose size is rawLen.
// There should be no missing nor unused byte.
AVIF_CHECKERR(avifROStreamRemainingBytes(&s) == (uint64_t)iccDataSize + tmapIccDataSize + gainmapMetadataSize + alphaItemDataSize +
gainmapItemDataSize + mainItemDataSize + exifDataSize + xmpDataSize,
AVIF_RESULT_BMFF_PARSE_FAILED);
// Create the items and properties generated by the MinimizedImageBox.
// The MinimizedImageBox always creates 8 properties for specification easiness.
// Use FreeSpaceBoxes as no-op placeholder properties when necessary.
// There is no need to use placeholder items because item IDs do not have to
// be contiguous, whereas property indices shall be 1, 2, 3, 4, 5 etc.
meta->primaryItemID = 1;
avifDecoderItem * colorItem;
AVIF_CHECKRES(avifMetaFindOrCreateItem(meta, meta->primaryItemID, &colorItem));
memcpy(colorItem->type, infeType, 4);
colorItem->width = width;
colorItem->height = height;
colorItem->miniBoxPixelFormat = chromaSubsampling == 0 ? AVIF_PIXEL_FORMAT_YUV400
: chromaSubsampling == 1 ? AVIF_PIXEL_FORMAT_YUV420
: chromaSubsampling == 2 ? AVIF_PIXEL_FORMAT_YUV422
: AVIF_PIXEL_FORMAT_YUV444;
if (colorItem->miniBoxPixelFormat == AVIF_PIXEL_FORMAT_YUV422) {
// In AV1, the chroma_sample_position syntax element is not present for the YUV 4:2:2 format.
// Assume that AV1 uses the same 4:2:2 chroma sample location as HEVC and VVC (colocated).
AVIF_CHECKERR(!chromaIsHorizontallyCentered, AVIF_RESULT_BMFF_PARSE_FAILED);
// chromaIsVerticallyCentered: Ignored unless chroma_subsampling is 1.
colorItem->miniBoxChromaSamplePosition = AVIF_CHROMA_SAMPLE_POSITION_UNKNOWN;
} else if (colorItem->miniBoxPixelFormat == AVIF_PIXEL_FORMAT_YUV420) {
if (chromaIsHorizontallyCentered) {
// There is no way to describe this with AV1's chroma_sample_position enum besides CSP_UNKNOWN.
// There is a proposal to assign the reserved value 3 (CSP_RESERVED) to the center chroma sample position.
colorItem->miniBoxChromaSamplePosition = AVIF_CHROMA_SAMPLE_POSITION_UNKNOWN;
} else {
colorItem->miniBoxChromaSamplePosition = chromaIsVerticallyCentered ? AVIF_CHROMA_SAMPLE_POSITION_VERTICAL
: AVIF_CHROMA_SAMPLE_POSITION_COLOCATED;
}
} else {
// chromaIsHorizontallyCentered: Ignored unless chroma_subsampling is 1 or 2.
// chromaIsVerticallyCentered: Ignored unless chroma_subsampling is 1.
colorItem->miniBoxChromaSamplePosition = AVIF_CHROMA_SAMPLE_POSITION_UNKNOWN;
}
avifDecoderItem * alphaItem = NULL;
if (hasAlpha) {
AVIF_CHECKRES(avifMetaFindOrCreateItem(meta, /*itemID=*/2, &alphaItem));
memcpy(alphaItem->type, infeType, 4);
alphaItem->width = width;
alphaItem->height = height;
alphaItem->miniBoxPixelFormat = AVIF_PIXEL_FORMAT_YUV400;
alphaItem->miniBoxChromaSamplePosition = AVIF_CHROMA_SAMPLE_POSITION_UNKNOWN;
}
avifDecoderItem * tmapItem = NULL;
if (hasGainmap) {
AVIF_CHECKRES(avifMetaFindOrCreateItem(meta, /*itemID=*/3, &tmapItem));
memcpy(tmapItem->type, "tmap", 4);
colorItem->dimgForID = tmapItem->id;
colorItem->dimgIdx = 0;
// avifDecoderReset() requires the 'tmap' item to be an alternative to the primary item.
avifEntityToGroup * group = avifArrayPush(&data->meta->entityToGroups);
AVIF_CHECKERR(group != NULL, AVIF_RESULT_OUT_OF_MEMORY);
memcpy(group->groupingType, "altr", 4);
AVIF_CHECKERR(avifArrayCreate(&group->entityIDs, sizeof(uint32_t), 2), AVIF_RESULT_OUT_OF_MEMORY);
uint32_t * groupEntityId = avifArrayPush(&group->entityIDs);
AVIF_CHECKERR(groupEntityId != NULL, AVIF_RESULT_OUT_OF_MEMORY);
*groupEntityId = tmapItem->id;
groupEntityId = avifArrayPush(&group->entityIDs);
AVIF_CHECKERR(groupEntityId != NULL, AVIF_RESULT_OUT_OF_MEMORY);
*groupEntityId = colorItem->id;
}
avifDecoderItem * gainmapItem = NULL;
if (gainmapItemDataSize != 0) {
AVIF_CHECKRES(avifMetaFindOrCreateItem(meta, /*itemID=*/4, &gainmapItem));
memcpy(gainmapItem->type, infeType, 4);
gainmapItem->width = gainmapWidth;
gainmapItem->height = gainmapHeight;
gainmapItem->dimgForID = tmapItem->id;
gainmapItem->dimgIdx = 1;
}
// Property with fixed index 1.
avifProperty * colorCodecConfigProp = avifMetaCreateProperty(meta, (const char *)codecConfigType);
AVIF_CHECKERR(colorCodecConfigProp, AVIF_RESULT_OUT_OF_MEMORY);
colorCodecConfigProp->u.av1C = mainItemCodecConfig;
AVIF_CHECKERR(avifDecoderItemAddProperty(colorItem, colorCodecConfigProp), AVIF_RESULT_OUT_OF_MEMORY);
// Property with fixed index 2.
avifProperty * ispeProp = avifMetaCreateProperty(meta, "ispe");
AVIF_CHECKERR(ispeProp, AVIF_RESULT_OUT_OF_MEMORY);
ispeProp->u.ispe.width = width;
ispeProp->u.ispe.height = height;
AVIF_CHECKERR(avifDecoderItemAddProperty(colorItem, ispeProp), AVIF_RESULT_OUT_OF_MEMORY);
// Property with fixed index 3.
avifProperty * pixiProp = avifMetaCreateProperty(meta, "pixi");
AVIF_CHECKERR(pixiProp, AVIF_RESULT_OUT_OF_MEMORY);
pixiProp->u.pixi.planeCount = chromaSubsampling == 0 ? 1 : 3;
for (uint8_t plane = 0; plane < pixiProp->u.pixi.planeCount; ++plane) {
pixiProp->u.pixi.planeDepths[plane] = (uint8_t)bitDepth;
}
AVIF_CHECKERR(avifDecoderItemAddProperty(colorItem, pixiProp), AVIF_RESULT_OUT_OF_MEMORY);
// Property with fixed index 4.
avifProperty * colrPropNCLX = avifMetaCreateProperty(meta, "colr");
AVIF_CHECKERR(colrPropNCLX, AVIF_RESULT_OUT_OF_MEMORY);
colrPropNCLX->u.colr.hasNCLX = AVIF_TRUE; // colour_type "nclx"
colrPropNCLX->u.colr.colorPrimaries = (avifColorPrimaries)colorPrimaries;
colrPropNCLX->u.colr.transferCharacteristics = (avifTransferCharacteristics)transferCharacteristics;
colrPropNCLX->u.colr.matrixCoefficients = (avifMatrixCoefficients)matrixCoefficients;
colrPropNCLX->u.colr.range = fullRange ? AVIF_RANGE_FULL : AVIF_RANGE_LIMITED;
AVIF_CHECKERR(avifDecoderItemAddProperty(colorItem, colrPropNCLX), AVIF_RESULT_OUT_OF_MEMORY);
// Property with fixed index 5.
if (iccDataSize != 0) {
avifProperty * colrPropICC = avifMetaCreateProperty(meta, "colr");
AVIF_CHECKERR(colrPropICC, AVIF_RESULT_OUT_OF_MEMORY);
colrPropICC->u.colr.hasICC = AVIF_TRUE; // colour_type "rICC" or "prof"
colrPropICC->u.colr.iccOffset = rawOffset + avifROStreamOffset(&s);
colrPropICC->u.colr.iccSize = (size_t)iccDataSize;
AVIF_CHECKERR(avifROStreamSkip(&s, colrPropICC->u.colr.iccSize), AVIF_RESULT_BMFF_PARSE_FAILED);
AVIF_CHECKERR(avifDecoderItemAddProperty(colorItem, colrPropICC), AVIF_RESULT_OUT_OF_MEMORY);
} else {
AVIF_CHECKERR(avifMetaCreateProperty(meta, "skip"), AVIF_RESULT_OUT_OF_MEMORY); // Placeholder.
}
if (alphaItemCodecConfigSize != 0) {
// Property with fixed index 6.
avifProperty * alphaCodecConfigProp = avifMetaCreateProperty(meta, (const char *)codecConfigType);
AVIF_CHECKERR(alphaCodecConfigProp, AVIF_RESULT_OUT_OF_MEMORY);
alphaCodecConfigProp->u.av1C = alphaItemCodecConfig;
AVIF_CHECKERR(avifDecoderItemAddProperty(alphaItem, alphaCodecConfigProp), AVIF_RESULT_OUT_OF_MEMORY);
} else {
AVIF_CHECKERR(avifMetaCreateProperty(meta, "skip"), AVIF_RESULT_OUT_OF_MEMORY); // Placeholder.
}
if (hasAlpha) {
// Property with fixed index 7.
alphaItem->auxForID = colorItem->id;
colorItem->premByID = alphaIsPremultiplied;
avifProperty * alphaAuxProp = avifMetaCreateProperty(meta, "auxC");
AVIF_CHECKERR(alphaAuxProp, AVIF_RESULT_OUT_OF_MEMORY);
strcpy(alphaAuxProp->u.auxC.auxType, AVIF_URN_ALPHA0);
AVIF_CHECKERR(avifDecoderItemAddProperty(alphaItem, alphaAuxProp), AVIF_RESULT_OUT_OF_MEMORY);
// Property with fixed index 2 (reused).
AVIF_CHECKERR(avifDecoderItemAddProperty(alphaItem, ispeProp), AVIF_RESULT_OUT_OF_MEMORY);
// Property with fixed index 8.
avifProperty * alphaPixiProp = avifMetaCreateProperty(meta, "pixi");
AVIF_CHECKERR(alphaPixiProp, AVIF_RESULT_OUT_OF_MEMORY);
memcpy(alphaPixiProp->type, "pixi", 4);
alphaPixiProp->u.pixi.planeCount = 1;
alphaPixiProp->u.pixi.planeDepths[0] = (uint8_t)bitDepth;
AVIF_CHECKERR(avifDecoderItemAddProperty(alphaItem, alphaPixiProp), AVIF_RESULT_OUT_OF_MEMORY);
} else {
// Placeholders 7 and 8.
AVIF_CHECKERR(avifMetaCreateProperty(meta, "skip"), AVIF_RESULT_OUT_OF_MEMORY);
AVIF_CHECKERR(avifMetaCreateProperty(meta, "skip"), AVIF_RESULT_OUT_OF_MEMORY);
}
uint32_t irotPropIndex = 0; // 0-based.
uint32_t imirPropIndex = 0;
// Same behavior as avifImageExtractExifOrientationToIrotImir().
if (orientation == 3 || orientation == 5 || orientation == 6 || orientation == 7 || orientation == 8) {
irotPropIndex = meta->properties.count; // Store index instead of pointer which may be invalidated by avifMetaCreateProperty().
// Property with fixed 1-based index 9.
assert(irotPropIndex + 1 == 9);
avifProperty * irotProp = avifMetaCreateProperty(meta, "irot");
AVIF_CHECKERR(irotProp, AVIF_RESULT_OUT_OF_MEMORY);
irotProp->u.irot.angle = orientation == 3 ? 2 : (orientation == 5 || orientation == 8) ? 1 : 3;
} else {
AVIF_CHECKERR(avifMetaCreateProperty(meta, "skip"), AVIF_RESULT_OUT_OF_MEMORY); // Placeholder.
}
if (orientation == 2 || orientation == 4 || orientation == 5 || orientation == 7) {
imirPropIndex = meta->properties.count;
// Property with fixed 1-based index 10.
assert(imirPropIndex + 1 == 10);
avifProperty * imirProp = avifMetaCreateProperty(meta, "imir");
AVIF_CHECKERR(imirProp, AVIF_RESULT_OUT_OF_MEMORY);
imirProp->u.imir.axis = orientation == 2 ? 1 : 0;
} else {
AVIF_CHECKERR(avifMetaCreateProperty(meta, "skip"), AVIF_RESULT_OUT_OF_MEMORY); // Placeholder.
}
if (hasClli) {
// Property with fixed index 11.
avifProperty * clliProp = avifMetaCreateProperty(meta, "clli");
AVIF_CHECKERR(clliProp, AVIF_RESULT_OUT_OF_MEMORY);
clliProp->u.clli = clli;
AVIF_CHECKERR(avifDecoderItemAddProperty(colorItem, clliProp), AVIF_RESULT_OUT_OF_MEMORY);
} else {
AVIF_CHECKERR(avifMetaCreateProperty(meta, "skip"), AVIF_RESULT_OUT_OF_MEMORY); // Placeholder.
}
// Properties with fixed indices 12 to 16 are ignored by libavif (mdcv, cclv, amve, reve and ndwt).
for (int i = 12; i <= 16; ++i) {
AVIF_CHECKERR(avifMetaCreateProperty(meta, "skip"), AVIF_RESULT_OUT_OF_MEMORY); // Placeholder.
}
if (gainmapItemCodecConfigSize != 0) {
// Property with fixed index 17.
avifProperty * gainmapCodecConfigProp = avifMetaCreateProperty(meta, (const char *)codecConfigType);
AVIF_CHECKERR(gainmapCodecConfigProp, AVIF_RESULT_OUT_OF_MEMORY);
gainmapCodecConfigProp->u.av1C = gainmapItemCodecConfig;
AVIF_CHECKERR(avifDecoderItemAddProperty(gainmapItem, gainmapCodecConfigProp), AVIF_RESULT_OUT_OF_MEMORY);
} else {
AVIF_CHECKERR(avifMetaCreateProperty(meta, "skip"), AVIF_RESULT_OUT_OF_MEMORY); // Placeholder.
}
if (gainmapItemDataSize != 0) {
// Property with fixed index 18.
avifProperty * gainmapIspeProp = avifMetaCreateProperty(meta, "ispe");
AVIF_CHECKERR(gainmapIspeProp, AVIF_RESULT_OUT_OF_MEMORY);
gainmapIspeProp->u.ispe.width = gainmapWidth;
gainmapIspeProp->u.ispe.height = gainmapHeight;
AVIF_CHECKERR(avifDecoderItemAddProperty(gainmapItem, gainmapIspeProp), AVIF_RESULT_OUT_OF_MEMORY);
// Property with fixed index 19.
avifProperty * gainmapPixiProp = avifMetaCreateProperty(meta, "pixi");
AVIF_CHECKERR(gainmapPixiProp, AVIF_RESULT_OUT_OF_MEMORY);
memcpy(gainmapPixiProp->type, "pixi", 4);
gainmapPixiProp->u.pixi.planeCount = gainmapChromaSubsampling == 0 ? 1 : 3;
for (uint8_t plane = 0; plane < gainmapPixiProp->u.pixi.planeCount; ++plane) {
gainmapPixiProp->u.pixi.planeDepths[plane] = (uint8_t)gainmapBitDepth;
}
AVIF_CHECKERR(avifDecoderItemAddProperty(gainmapItem, gainmapPixiProp), AVIF_RESULT_OUT_OF_MEMORY);
// Property with fixed index 20.
avifProperty * gainmapColrPropNCLX = avifMetaCreateProperty(meta, "colr");
AVIF_CHECKERR(gainmapColrPropNCLX, AVIF_RESULT_OUT_OF_MEMORY);
gainmapColrPropNCLX->u.colr.hasNCLX = AVIF_TRUE; // colour_type "nclx"
gainmapColrPropNCLX->u.colr.colorPrimaries = AVIF_COLOR_PRIMARIES_UNSPECIFIED; // 2
gainmapColrPropNCLX->u.colr.transferCharacteristics = AVIF_TRANSFER_CHARACTERISTICS_UNSPECIFIED; // 2
gainmapColrPropNCLX->u.colr.matrixCoefficients = (avifMatrixCoefficients)gainmapMatrixCoefficients;
gainmapColrPropNCLX->u.colr.range = gainmapFullRange ? AVIF_RANGE_FULL : AVIF_RANGE_LIMITED;
AVIF_CHECKERR(avifDecoderItemAddProperty(gainmapItem, gainmapColrPropNCLX), AVIF_RESULT_OUT_OF_MEMORY);
} else {
// Placeholders 18, 19 and 20.
AVIF_CHECKERR(avifMetaCreateProperty(meta, "skip"), AVIF_RESULT_OUT_OF_MEMORY);
AVIF_CHECKERR(avifMetaCreateProperty(meta, "skip"), AVIF_RESULT_OUT_OF_MEMORY);
AVIF_CHECKERR(avifMetaCreateProperty(meta, "skip"), AVIF_RESULT_OUT_OF_MEMORY);
}
if (hasGainmap) {
// Property with fixed index 21.
avifProperty * tmapIspeProp = avifMetaCreateProperty(meta, "ispe");
AVIF_CHECKERR(tmapIspeProp, AVIF_RESULT_OUT_OF_MEMORY);
tmapIspeProp->u.ispe.width = orientation <= 4 ? width : height;
tmapIspeProp->u.ispe.height = orientation <= 4 ? height : width;
AVIF_CHECKERR(avifDecoderItemAddProperty(tmapItem, tmapIspeProp), AVIF_RESULT_OUT_OF_MEMORY);
} else {
AVIF_CHECKERR(avifMetaCreateProperty(meta, "skip"), AVIF_RESULT_OUT_OF_MEMORY); // Placeholder.
}
if (hasGainmap && (tmapHasExplicitCicp || !tmapHasIcc)) {
// Property with fixed index 22.
avifProperty * tmapColrPropNCLX = avifMetaCreateProperty(meta, "colr");
AVIF_CHECKERR(tmapColrPropNCLX, AVIF_RESULT_OUT_OF_MEMORY);
tmapColrPropNCLX->u.colr.hasNCLX = AVIF_TRUE; // colour_type "nclx"
tmapColrPropNCLX->u.colr.colorPrimaries = (avifColorPrimaries)tmapColorPrimaries;
tmapColrPropNCLX->u.colr.transferCharacteristics = (avifTransferCharacteristics)tmapTransferCharacteristics;
tmapColrPropNCLX->u.colr.matrixCoefficients = (avifMatrixCoefficients)tmapMatrixCoefficients;
tmapColrPropNCLX->u.colr.range = tmapFullRange ? AVIF_RANGE_FULL : AVIF_RANGE_LIMITED;
AVIF_CHECKERR(avifDecoderItemAddProperty(tmapItem, tmapColrPropNCLX), AVIF_RESULT_OUT_OF_MEMORY);
} else {
AVIF_CHECKERR(avifMetaCreateProperty(meta, "skip"), AVIF_RESULT_OUT_OF_MEMORY); // Placeholder.
}
if (tmapIccDataSize != 0) {
// Property with fixed index 23.
avifProperty * tmapColrPropICC = avifMetaCreateProperty(meta, "colr");
AVIF_CHECKERR(tmapColrPropICC, AVIF_RESULT_OUT_OF_MEMORY);
tmapColrPropICC->u.colr.hasICC = AVIF_TRUE; // colour_type "rICC" or "prof"
tmapColrPropICC->u.colr.iccOffset = rawOffset + avifROStreamOffset(&s);
tmapColrPropICC->u.colr.iccSize = tmapIccDataSize;
AVIF_CHECKERR(avifROStreamSkip(&s, tmapColrPropICC->u.colr.iccSize), AVIF_RESULT_BMFF_PARSE_FAILED);
AVIF_CHECKERR(avifDecoderItemAddProperty(colorItem, tmapColrPropICC), AVIF_RESULT_OUT_OF_MEMORY);
} else {
AVIF_CHECKERR(avifMetaCreateProperty(meta, "skip"), AVIF_RESULT_OUT_OF_MEMORY); // Placeholder.
}
if (tmapHasClli) {
// Property with fixed index 24.
avifProperty * tmapClliProp = avifMetaCreateProperty(meta, "clli");
AVIF_CHECKERR(tmapClliProp, AVIF_RESULT_OUT_OF_MEMORY);
tmapClliProp->u.clli = tmapClli;
AVIF_CHECKERR(avifDecoderItemAddProperty(tmapItem, tmapClliProp), AVIF_RESULT_OUT_OF_MEMORY);
} else {
AVIF_CHECKERR(avifMetaCreateProperty(meta, "skip"), AVIF_RESULT_OUT_OF_MEMORY); // Placeholder.
}
// Properties with fixed indices 25 to 29 are ignored by libavif (mdcv, cclv, amve, reve and ndwt).
for (int i = 25; i <= 29; ++i) {
AVIF_CHECKERR(avifMetaCreateProperty(meta, "skip"), AVIF_RESULT_OUT_OF_MEMORY); // Placeholder.
}
AVIF_ASSERT_OR_RETURN(meta->properties.count == 29);
// ISO/IEC 23008-12 Section 6.5.1:
// Writers should arrange the descriptive properties specified in 6.5 prior to any other properties in the
// sequence associating properties with an item.
//
// irot and imir are transformative properties, so associate them last.
if (irotPropIndex != 0) {
const avifProperty * irotProp = &meta->properties.prop[irotPropIndex];
AVIF_CHECKERR(avifDecoderItemAddProperty(colorItem, irotProp), AVIF_RESULT_OUT_OF_MEMORY);
if (hasAlpha) {
AVIF_CHECKERR(avifDecoderItemAddProperty(alphaItem, irotProp), AVIF_RESULT_OUT_OF_MEMORY);
}
if (gainmapItemDataSize != 0) {
AVIF_CHECKERR(avifDecoderItemAddProperty(gainmapItem, irotProp), AVIF_RESULT_OUT_OF_MEMORY);
}
}
if (imirPropIndex != 0) {
const avifProperty * imirProp = &meta->properties.prop[imirPropIndex];
AVIF_CHECKERR(avifDecoderItemAddProperty(colorItem, imirProp), AVIF_RESULT_OUT_OF_MEMORY);
if (hasAlpha) {
AVIF_CHECKERR(avifDecoderItemAddProperty(alphaItem, imirProp), AVIF_RESULT_OUT_OF_MEMORY);
}
if (gainmapItemDataSize != 0) {
AVIF_CHECKERR(avifDecoderItemAddProperty(gainmapItem, imirProp), AVIF_RESULT_OUT_OF_MEMORY);
}
}
// Extents.
if (gainmapMetadataSize != 0) {
// Prepend the version field to the GainMapMetadata to form the ToneMapImage syntax.
tmapItem->size = gainmapMetadataSize + 1;
AVIF_CHECKRES(avifRWDataRealloc(&tmapItem->mergedExtents, tmapItem->size));
tmapItem->ownsMergedExtents = AVIF_TRUE;
tmapItem->mergedExtents.data[0] = 0; // unsigned int(8) version = 0;
AVIF_CHECKERR(avifROStreamRead(&s, tmapItem->mergedExtents.data + 1, gainmapMetadataSize), AVIF_RESULT_BMFF_PARSE_FAILED);
}
if (hasAlpha) {
avifExtent * alphaExtent = (avifExtent *)avifArrayPush(&alphaItem->extents);
AVIF_CHECKERR(alphaExtent, AVIF_RESULT_OUT_OF_MEMORY);
alphaExtent->offset = rawOffset + avifROStreamOffset(&s);
alphaExtent->size = alphaItemDataSize;
AVIF_CHECKERR(avifROStreamSkip(&s, alphaExtent->size), AVIF_RESULT_BMFF_PARSE_FAILED);
alphaItem->size = alphaExtent->size;
}
if (gainmapItemDataSize != 0) {
avifExtent * gainmapExtent = (avifExtent *)avifArrayPush(&gainmapItem->extents);
AVIF_CHECKERR(gainmapExtent, AVIF_RESULT_OUT_OF_MEMORY);
gainmapExtent->offset = rawOffset + avifROStreamOffset(&s);
gainmapExtent->size = gainmapItemDataSize;
AVIF_CHECKERR(avifROStreamSkip(&s, gainmapExtent->size), AVIF_RESULT_BMFF_PARSE_FAILED);
gainmapItem->size = gainmapExtent->size;
}
avifExtent * colorExtent = (avifExtent *)avifArrayPush(&colorItem->extents);
AVIF_CHECKERR(colorExtent, AVIF_RESULT_OUT_OF_MEMORY);
colorExtent->offset = rawOffset + avifROStreamOffset(&s);
colorExtent->size = mainItemDataSize;
AVIF_CHECKERR(avifROStreamSkip(&s, colorExtent->size), AVIF_RESULT_BMFF_PARSE_FAILED);
colorItem->size = colorExtent->size;
if (hasExif) {
avifDecoderItem * exifItem;
AVIF_CHECKRES(avifMetaFindOrCreateItem(meta, /*itemID=*/6, &exifItem));
memcpy(exifItem->type, "Exif", 4);
exifItem->descForID = colorItem->id; // 'cdsc'
avifExtent * exifExtent = (avifExtent *)avifArrayPush(&exifItem->extents);
AVIF_CHECKERR(exifExtent, AVIF_RESULT_OUT_OF_MEMORY);
exifExtent->offset = rawOffset + avifROStreamOffset(&s);
exifExtent->size = exifDataSize; // Does not include unsigned int(32) exif_tiff_header_offset;
AVIF_CHECKERR(avifROStreamSkip(&s, exifExtent->size), AVIF_RESULT_BMFF_PARSE_FAILED);
exifItem->size = exifExtent->size;
}
if (hasXmp) {
avifDecoderItem * xmpItem;
AVIF_CHECKRES(avifMetaFindOrCreateItem(meta, /*itemID=*/7, &xmpItem));
memcpy(xmpItem->type, "mime", 4);
memcpy(xmpItem->contentType.contentType, AVIF_CONTENT_TYPE_XMP, sizeof(AVIF_CONTENT_TYPE_XMP));
xmpItem->descForID = colorItem->id; // 'cdsc'
avifExtent * xmpExtent = (avifExtent *)avifArrayPush(&xmpItem->extents);
AVIF_CHECKERR(xmpExtent, AVIF_RESULT_OUT_OF_MEMORY);
xmpExtent->offset = rawOffset + avifROStreamOffset(&s);
xmpExtent->size = xmpDataSize;
AVIF_CHECKERR(avifROStreamSkip(&s, xmpExtent->size), AVIF_RESULT_BMFF_PARSE_FAILED);
xmpItem->size = xmpExtent->size;
}
return AVIF_RESULT_OK;
}
#endif // AVIF_ENABLE_EXPERIMENTAL_MINI
static avifBool avifParseFileTypeBox(avifFileType * ftyp, const uint8_t * raw, size_t rawLen, avifDiagnostics * diag)
{
BEGIN_STREAM(s, raw, rawLen, diag, "Box[ftyp]");
AVIF_CHECK(avifROStreamRead(&s, ftyp->majorBrand, 4));
AVIF_CHECK(avifROStreamRead(&s, ftyp->minorVersion, 4));
size_t compatibleBrandsBytes = avifROStreamRemainingBytes(&s);
if ((compatibleBrandsBytes % 4) != 0) {
avifDiagnosticsPrintf(diag, "Box[ftyp] contains a compatible brands section that isn't divisible by 4 [%zu]", compatibleBrandsBytes);
return AVIF_FALSE;
}
ftyp->compatibleBrands = avifROStreamCurrent(&s);
AVIF_CHECK(avifROStreamSkip(&s, compatibleBrandsBytes));
ftyp->compatibleBrandsCount = (int)compatibleBrandsBytes / 4;
return AVIF_TRUE;
}
static avifBool avifFileTypeHasBrand(avifFileType * ftyp, const char * brand);
static avifBool avifFileTypeIsCompatible(avifFileType * ftyp);
static avifResult avifParse(avifDecoder * decoder)
{
// Note: this top-level function is the only avifParse*() function that returns avifResult instead of avifBool.
// Be sure to use AVIF_CHECKERR() in this function with an explicit error result instead of simply using AVIF_CHECK().
avifResult readResult;
uint64_t parseOffset = 0;
avifDecoderData * data = decoder->data;
avifBool ftypSeen = AVIF_FALSE;
avifBool metaSeen = AVIF_FALSE;
avifBool metaIsSizeZero = AVIF_FALSE;
avifBool moovSeen = AVIF_FALSE;
avifBool needsMeta = AVIF_FALSE;
avifBool needsMoov = AVIF_FALSE;
#if defined(AVIF_ENABLE_EXPERIMENTAL_MINI)
avifBool miniSeen = AVIF_FALSE;
avifBool needsMini = AVIF_FALSE;
#endif
avifBool needsTmap = AVIF_FALSE;
avifBool tmapSeen = AVIF_FALSE;
avifFileType ftyp = { 0 };
for (;;) {
// Read just enough to get the next box header (a max of 32 bytes)
avifROData headerContents;
if ((decoder->io->sizeHint > 0) && (parseOffset > decoder->io->sizeHint)) {
return AVIF_RESULT_BMFF_PARSE_FAILED;
}
readResult = decoder->io->read(decoder->io, 0, parseOffset, 32, &headerContents);
if (readResult != AVIF_RESULT_OK) {
return readResult;
}
if (!headerContents.size) {
// If we got AVIF_RESULT_OK from the reader but received 0 bytes,
// we've reached the end of the file with no errors. Hooray!
break;
}
// Parse the header, and find out how many bytes it actually was
BEGIN_STREAM(headerStream, headerContents.data, headerContents.size, &decoder->diag, "File-level box header");
avifBoxHeader header;
AVIF_CHECKERR(avifROStreamReadBoxHeaderPartial(&headerStream, &header, /*topLevel=*/AVIF_TRUE), AVIF_RESULT_BMFF_PARSE_FAILED);
parseOffset += headerStream.offset;
AVIF_ASSERT_OR_RETURN(decoder->io->sizeHint == 0 || parseOffset <= decoder->io->sizeHint);
// Try to get the remainder of the box, if necessary
uint64_t boxOffset = 0;
avifROData boxContents = AVIF_DATA_EMPTY;
avifBool isFtyp = AVIF_FALSE, isMeta = AVIF_FALSE, isMoov = AVIF_FALSE;
avifBool isNonSkippableVariableLengthBox = AVIF_FALSE;
if (!memcmp(header.type, "ftyp", 4)) {
isFtyp = AVIF_TRUE;
isNonSkippableVariableLengthBox = AVIF_TRUE;
} else if (!memcmp(header.type, "meta", 4)) {
isMeta = AVIF_TRUE;
isNonSkippableVariableLengthBox = AVIF_TRUE;
metaIsSizeZero = header.isSizeZeroBox;
} else if (!memcmp(header.type, "moov", 4)) {
isMoov = AVIF_TRUE;
isNonSkippableVariableLengthBox = AVIF_TRUE;
}
#if defined(AVIF_ENABLE_EXPERIMENTAL_MINI)
avifBool isMini = AVIF_FALSE;
if (!isNonSkippableVariableLengthBox && !memcmp(header.type, "mini", 4)) {
isMini = AVIF_TRUE;
isNonSkippableVariableLengthBox = AVIF_TRUE;
}
#endif
if (!isFtyp && (isNonSkippableVariableLengthBox || !memcmp(header.type, "free", 4) || !memcmp(header.type, "skip", 4) ||
!memcmp(header.type, "mdat", 4))) {
// Section 6.3.4 of ISO/IEC 14496-12:
// The FileTypeBox shall occur before any variable-length box (e.g. movie, free space, media data).
AVIF_CHECKERR(ftypSeen, AVIF_RESULT_BMFF_PARSE_FAILED);
}
if (isNonSkippableVariableLengthBox) {
boxOffset = parseOffset;
size_t sizeToRead;
if (header.isSizeZeroBox) {
// The box body goes till the end of the file.
if (decoder->io->sizeHint != 0 && decoder->io->sizeHint - parseOffset < SIZE_MAX) {
sizeToRead = (size_t)(decoder->io->sizeHint - parseOffset);
} else {
sizeToRead = SIZE_MAX; // This will get truncated. See the documentation of avifIOReadFunc.
}
} else {
sizeToRead = header.size;
}
readResult = decoder->io->read(decoder->io, 0, parseOffset, sizeToRead, &boxContents);
if (readResult != AVIF_RESULT_OK) {
return readResult;
}
if (header.isSizeZeroBox) {
header.size = boxContents.size;
} else if (boxContents.size != header.size) {
// A truncated box, bail out
return AVIF_RESULT_TRUNCATED_DATA;
}
} else if (header.isSizeZeroBox) {
// An unknown top level box with size 0 was found. If we reach here it means we haven't completed parsing successfully
// since there are no further boxes left.
return AVIF_RESULT_BMFF_PARSE_FAILED;
} else if (header.size > (UINT64_MAX - parseOffset)) {
return AVIF_RESULT_BMFF_PARSE_FAILED;
}
parseOffset += header.size;
if (isFtyp) {
AVIF_CHECKERR(!ftypSeen, AVIF_RESULT_BMFF_PARSE_FAILED);
AVIF_CHECKERR(avifParseFileTypeBox(&ftyp, boxContents.data, boxContents.size, data->diag), AVIF_RESULT_BMFF_PARSE_FAILED);
AVIF_CHECKERR(avifFileTypeIsCompatible(&ftyp), AVIF_RESULT_INVALID_FTYP);
ftypSeen = AVIF_TRUE;
memcpy(data->majorBrand, ftyp.majorBrand, 4); // Remember the major brand for future AVIF_DECODER_SOURCE_AUTO decisions
if (ftyp.compatibleBrandsCount > 0) {
AVIF_CHECKERR(avifArrayCreate(&data->compatibleBrands, sizeof(avifBrand), ftyp.compatibleBrandsCount),
AVIF_RESULT_OUT_OF_MEMORY);
memcpy(data->compatibleBrands.brand, ftyp.compatibleBrands, sizeof(avifBrand) * ftyp.compatibleBrandsCount);
data->compatibleBrands.count = ftyp.compatibleBrandsCount;
}
needsMeta = avifFileTypeHasBrand(&ftyp, "avif");
needsMoov = avifFileTypeHasBrand(&ftyp, "avis");
#if defined(AVIF_ENABLE_EXPERIMENTAL_MINI)
needsMini = avifFileTypeHasBrand(&ftyp, "mif3");
if (needsMini) {
AVIF_CHECKERR(!needsMeta, AVIF_RESULT_INVALID_FTYP);
// Section O.2.1.2 of ISO/IEC 23008-12:2014, CDAM 2:
// When the 'mif3' brand is present as the major_brand of the FileTypeBox,
// the minor_version of the FileTypeBox shall be 0 or a brand that is either
// structurally compatible with the 'mif3' brand, such as a codec brand
// complying with the 'mif3' structural brand, or a brand to which the file
// conforms after the equivalent MetaBox has been transformed from
// MinimizedImageBox as specified in Clause O.4.
AVIF_CHECKERR(!memcmp(ftyp.minorVersion, "\0\0\0\0", 4) || !memcmp(ftyp.minorVersion, "avif", 4),
AVIF_RESULT_BMFF_PARSE_FAILED);
}
#endif // AVIF_ENABLE_EXPERIMENTAL_MINI
needsTmap = avifFileTypeHasBrand(&ftyp, "tmap");
if (needsTmap) {
needsMeta = AVIF_TRUE;
}
} else if (isMeta) {
AVIF_CHECKERR(!metaSeen, AVIF_RESULT_BMFF_PARSE_FAILED);
#if defined(AVIF_ENABLE_EXPERIMENTAL_MINI)
AVIF_CHECKERR(!miniSeen, AVIF_RESULT_BMFF_PARSE_FAILED);
#endif
AVIF_CHECKRES(avifParseMetaBox(data->meta, boxOffset, boxContents.data, boxContents.size, data->diag));
metaSeen = AVIF_TRUE;
for (uint32_t itemIndex = 0; itemIndex < data->meta->items.count; ++itemIndex) {
if (!memcmp(data->meta->items.item[itemIndex]->type, "tmap", 4)) {
tmapSeen = AVIF_TRUE;
break;
}
}
#if defined(AVIF_ENABLE_EXPERIMENTAL_MINI)
} else if (isMini) {
AVIF_CHECKERR(!metaSeen, AVIF_RESULT_BMFF_PARSE_FAILED);
AVIF_CHECKERR(!miniSeen, AVIF_RESULT_BMFF_PARSE_FAILED);
const avifBool isAvifAccordingToMinorVersion = !memcmp(ftyp.minorVersion, "avif", 4);
AVIF_CHECKRES(
avifParseMinimizedImageBox(data, boxOffset, boxContents.data, boxContents.size, isAvifAccordingToMinorVersion, data->diag));
miniSeen = AVIF_TRUE;
#endif
} else if (isMoov) {
AVIF_CHECKERR(!moovSeen, AVIF_RESULT_BMFF_PARSE_FAILED);
AVIF_CHECKRES(
avifParseMovieBox(data, boxOffset, boxContents.data, boxContents.size, decoder->imageSizeLimit, decoder->imageDimensionLimit));
moovSeen = AVIF_TRUE;
decoder->imageSequenceTrackPresent = AVIF_TRUE;
}
#if defined(AVIF_ENABLE_EXPERIMENTAL_MINI)
if (ftypSeen && !needsMini) {
// When MinimizedImageBox is present in a file, the 'mif3' brand or a derived brand that implies the 'mif3'
// brand shall be the major brand or present among the compatible brands in the FileTypeBox.
AVIF_CHECKERR(!miniSeen, AVIF_RESULT_BMFF_PARSE_FAILED);
}
#endif // AVIF_ENABLE_EXPERIMENTAL_MINI
// See if there is enough information to consider Parse() a success and early-out:
// * If the brand 'avif' is present, require a meta box
// * If the brand 'avis' is present, require a moov box
// * If AVIF_ENABLE_EXPERIMENTAL_MINI is defined and the brand 'mif3' is present, require a mini box
avifBool sawEverythingNeeded = ftypSeen && (!needsMeta || metaSeen) && (!needsMoov || moovSeen) && (!needsTmap || tmapSeen);
#if defined(AVIF_ENABLE_EXPERIMENTAL_MINI)
sawEverythingNeeded = sawEverythingNeeded && (!needsMini || miniSeen);
#endif
if (sawEverythingNeeded) {
return AVIF_RESULT_OK;
}
}
if (!ftypSeen) {
return AVIF_RESULT_INVALID_FTYP;
}
if ((needsMeta && !metaSeen) || (needsMoov && !moovSeen)) {
return AVIF_RESULT_TRUNCATED_DATA;
}
if (needsTmap && !tmapSeen) {
return metaIsSizeZero ? AVIF_RESULT_TRUNCATED_DATA : AVIF_RESULT_BMFF_PARSE_FAILED;
}
#if defined(AVIF_ENABLE_EXPERIMENTAL_MINI)
if (needsMini && !miniSeen) {
return AVIF_RESULT_TRUNCATED_DATA;
}
#endif
return AVIF_RESULT_OK;
}
// ---------------------------------------------------------------------------
static avifBool avifFileTypeHasBrand(avifFileType * ftyp, const char * brand)
{
if (!memcmp(ftyp->majorBrand, brand, 4)) {
return AVIF_TRUE;
}
for (int compatibleBrandIndex = 0; compatibleBrandIndex < ftyp->compatibleBrandsCount; ++compatibleBrandIndex) {
const uint8_t * compatibleBrand = &ftyp->compatibleBrands[4 * compatibleBrandIndex];
if (!memcmp(compatibleBrand, brand, 4)) {
return AVIF_TRUE;
}
}
return AVIF_FALSE;
}
static avifBool avifFileTypeIsCompatible(avifFileType * ftyp)
{
return avifFileTypeHasBrand(ftyp, "avif") || avifFileTypeHasBrand(ftyp, "avis")
#if defined(AVIF_ENABLE_EXPERIMENTAL_MINI)
|| avifFileTypeHasBrand(ftyp, "mif3")
#endif // AVIF_ENABLE_EXPERIMENTAL_MINI
;
}
avifBool avifPeekCompatibleFileType(const avifROData * input)
{
BEGIN_STREAM(s, input->data, input->size, NULL, NULL);
avifBoxHeader header;
if (!avifROStreamReadBoxHeaderPartial(&s, &header, /*topLevel=*/AVIF_TRUE) || memcmp(header.type, "ftyp", 4)) {
return AVIF_FALSE;
}
if (header.isSizeZeroBox) {
// The ftyp box goes on till the end of the file. Either there is no brand requiring anything in the file but a
// FileTypebox (so not AVIF), or it is invalid.
return AVIF_FALSE;
}
AVIF_CHECK(avifROStreamHasBytesLeft(&s, header.size));
avifFileType ftyp;
memset(&ftyp, 0, sizeof(avifFileType));
avifBool parsed = avifParseFileTypeBox(&ftyp, avifROStreamCurrent(&s), header.size, NULL);
if (!parsed) {
return AVIF_FALSE;
}
return avifFileTypeIsCompatible(&ftyp);
}
static avifBool avifBrandArrayHasBrand(avifBrandArray * brands, const char * brand)
{
for (uint32_t brandIndex = 0; brandIndex < brands->count; ++brandIndex) {
if (!memcmp(brands->brand[brandIndex], brand, 4)) {
return AVIF_TRUE;
}
}
return AVIF_FALSE;
}
// ---------------------------------------------------------------------------
avifDecoder * avifDecoderCreate(void)
{
avifDecoder * decoder = (avifDecoder *)avifAlloc(sizeof(avifDecoder));
if (decoder == NULL) {
return NULL;
}
memset(decoder, 0, sizeof(avifDecoder));
decoder->maxThreads = 1;
decoder->imageSizeLimit = AVIF_DEFAULT_IMAGE_SIZE_LIMIT;
decoder->imageDimensionLimit = AVIF_DEFAULT_IMAGE_DIMENSION_LIMIT;
decoder->imageCountLimit = AVIF_DEFAULT_IMAGE_COUNT_LIMIT;
decoder->strictFlags = AVIF_STRICT_ENABLED;
decoder->imageContentToDecode = AVIF_IMAGE_CONTENT_DECODE_DEFAULT;
return decoder;
}
static void avifDecoderCleanup(avifDecoder * decoder)
{
if (decoder->data) {
avifDecoderDataDestroy(decoder->data);
decoder->data = NULL;
}
if (decoder->image) {
avifImageDestroy(decoder->image);
decoder->image = NULL;
}
avifDiagnosticsClearError(&decoder->diag);
}
void avifDecoderDestroy(avifDecoder * decoder)
{
avifDecoderCleanup(decoder);
avifIODestroy(decoder->io);
avifFree(decoder);
}
avifResult avifDecoderSetSource(avifDecoder * decoder, avifDecoderSource source)
{
decoder->requestedSource = source;
return avifDecoderReset(decoder);
}
void avifDecoderSetIO(avifDecoder * decoder, avifIO * io)
{
avifIODestroy(decoder->io);
decoder->io = io;
}
avifResult avifDecoderSetIOMemory(avifDecoder * decoder, const uint8_t * data, size_t size)
{
avifIO * io = avifIOCreateMemoryReader(data, size);
AVIF_CHECKERR(io != NULL, AVIF_RESULT_OUT_OF_MEMORY);
avifDecoderSetIO(decoder, io);
return AVIF_RESULT_OK;
}
avifResult avifDecoderSetIOFile(avifDecoder * decoder, const char * filename)
{
avifIO * io = avifIOCreateFileReader(filename);
if (!io) {
return AVIF_RESULT_IO_ERROR;
}
avifDecoderSetIO(decoder, io);
return AVIF_RESULT_OK;
}
// 0-byte extents are ignored/overwritten during the merge, as they are the signal from helper
// functions that no extent was necessary for this given sample. If both provided extents are
// >0 bytes, this will set dst to be an extent that bounds both supplied extents.
static avifResult avifExtentMerge(avifExtent * dst, const avifExtent * src)
{
if (!dst->size) {
*dst = *src;
return AVIF_RESULT_OK;
}
if (!src->size) {
return AVIF_RESULT_OK;
}
const uint64_t minExtent1 = dst->offset;
const uint64_t maxExtent1 = dst->offset + dst->size;
const uint64_t minExtent2 = src->offset;
const uint64_t maxExtent2 = src->offset + src->size;
dst->offset = AVIF_MIN(minExtent1, minExtent2);
const uint64_t extentLength = AVIF_MAX(maxExtent1, maxExtent2) - dst->offset;
#if UINT64_MAX > SIZE_MAX
if (extentLength > SIZE_MAX) {
return AVIF_RESULT_BMFF_PARSE_FAILED;
}
#endif
dst->size = (size_t)extentLength;
return AVIF_RESULT_OK;
}
avifResult avifDecoderNthImageMaxExtent(const avifDecoder * decoder, uint32_t frameIndex, avifExtent * outExtent)
{
if (!decoder->data) {
// Nothing has been parsed yet
return AVIF_RESULT_NO_CONTENT;
}
memset(outExtent, 0, sizeof(avifExtent));
uint32_t startFrameIndex = avifDecoderNearestKeyframe(decoder, frameIndex);
uint32_t endFrameIndex = frameIndex;
for (uint32_t currentFrameIndex = startFrameIndex; currentFrameIndex <= endFrameIndex; ++currentFrameIndex) {
for (unsigned int tileIndex = 0; tileIndex < decoder->data->tiles.count; ++tileIndex) {
avifTile * tile = &decoder->data->tiles.tile[tileIndex];
if (currentFrameIndex >= tile->input->samples.count) {
return AVIF_RESULT_NO_IMAGES_REMAINING;
}
avifDecodeSample * sample = &tile->input->samples.sample[currentFrameIndex];
avifExtent sampleExtent;
if (sample->itemID) {
// The data comes from an item. Let avifDecoderItemMaxExtent() do the heavy lifting.
avifDecoderItem * item;
AVIF_CHECKRES(avifMetaFindOrCreateItem(decoder->data->meta, sample->itemID, &item));
avifResult maxExtentResult = avifDecoderItemMaxExtent(item, sample, &sampleExtent);
if (maxExtentResult != AVIF_RESULT_OK) {
return maxExtentResult;
}
} else {
// The data likely comes from a sample table. Use the sample position directly.
sampleExtent.offset = sample->offset;
sampleExtent.size = sample->size;
}
if (sampleExtent.size > UINT64_MAX - sampleExtent.offset) {
return AVIF_RESULT_BMFF_PARSE_FAILED;
}
avifResult extentMergeResult = avifExtentMerge(outExtent, &sampleExtent);
if (extentMergeResult != AVIF_RESULT_OK) {
return extentMergeResult;
}
}
}
return AVIF_RESULT_OK;
}
static avifResult avifDecoderPrepareSample(avifDecoder * decoder, avifDecodeSample * sample, size_t partialByteCount)
{
if (!sample->data.size || sample->partialData) {
// This sample hasn't been read from IO or had its extents fully merged yet.
size_t bytesToRead = sample->size;
if (partialByteCount && (bytesToRead > partialByteCount)) {
bytesToRead = partialByteCount;
}
if (sample->itemID) {
// The data comes from an item. Let avifDecoderItemRead() do the heavy lifting.
avifDecoderItem * item;
AVIF_CHECKRES(avifMetaFindOrCreateItem(decoder->data->meta, sample->itemID, &item));
avifROData itemContents;
#if UINT64_MAX > SIZE_MAX
if (sample->offset > SIZE_MAX) {
return AVIF_RESULT_BMFF_PARSE_FAILED;
}
#endif
size_t offset = (size_t)sample->offset;
avifResult readResult = avifDecoderItemRead(item, decoder->io, &itemContents, offset, bytesToRead, &decoder->diag);
if (readResult != AVIF_RESULT_OK) {
return readResult;
}
// avifDecoderItemRead is guaranteed to already be persisted by either the underlying IO
// or by mergedExtents; just reuse the buffer here.
sample->data = itemContents;
sample->ownsData = AVIF_FALSE;
sample->partialData = item->partialMergedExtents;
} else {
// The data likely comes from a sample table. Pull the sample and make a copy if necessary.
avifROData sampleContents;
if ((decoder->io->sizeHint > 0) && (sample->offset > decoder->io->sizeHint)) {
return AVIF_RESULT_BMFF_PARSE_FAILED;
}
avifResult readResult = decoder->io->read(decoder->io, 0, sample->offset, bytesToRead, &sampleContents);
if (readResult != AVIF_RESULT_OK) {
return readResult;
}
if (sampleContents.size != bytesToRead) {
return AVIF_RESULT_TRUNCATED_DATA;
}
sample->ownsData = !decoder->io->persistent;
sample->partialData = (bytesToRead != sample->size);
if (decoder->io->persistent) {
sample->data = sampleContents;
} else {
AVIF_CHECKRES(avifRWDataSet((avifRWData *)&sample->data, sampleContents.data, sampleContents.size));
}
}
}
return AVIF_RESULT_OK;
}
// Returns AVIF_TRUE if the item should be skipped. Items should be skipped for one of the following reasons:
// * Size is 0.
// * Has an essential property that isn't supported by libavif.
// * Item is not a single image or a grid.
// * Item is a thumbnail.
static avifBool avifDecoderItemShouldBeSkipped(const avifDecoderItem * item)
{
return !item->size || item->hasUnsupportedEssentialProperty ||
(avifGetCodecType(item->type) == AVIF_CODEC_TYPE_UNKNOWN && memcmp(item->type, "grid", 4)) || item->thumbnailForID != 0;
}
avifResult avifDecoderParse(avifDecoder * decoder)
{
avifDiagnosticsClearError(&decoder->diag);
// An imageSizeLimit greater than AVIF_DEFAULT_IMAGE_SIZE_LIMIT and the special value of 0 to
// disable the limit are not yet implemented.
if ((decoder->imageSizeLimit > AVIF_DEFAULT_IMAGE_SIZE_LIMIT) || (decoder->imageSizeLimit == 0)) {
return AVIF_RESULT_NOT_IMPLEMENTED;
}
// Color only or alpha only is not currently supported.
if ((decoder->imageContentToDecode & AVIF_IMAGE_CONTENT_COLOR_AND_ALPHA) != 0 &&
(decoder->imageContentToDecode & AVIF_IMAGE_CONTENT_COLOR_AND_ALPHA) != AVIF_IMAGE_CONTENT_COLOR_AND_ALPHA) {
avifDiagnosticsPrintf(&decoder->diag, "imageContentToDecode set to only color or only alpha is not supported");
return AVIF_RESULT_NOT_IMPLEMENTED;
}
if (!decoder->io || !decoder->io->read) {
return AVIF_RESULT_IO_NOT_SET;
}
// Cleanup anything lingering in the decoder
avifDecoderCleanup(decoder);
// -----------------------------------------------------------------------
// Parse BMFF boxes
decoder->data = avifDecoderDataCreate();
AVIF_CHECKERR(decoder->data != NULL, AVIF_RESULT_OUT_OF_MEMORY);
decoder->data->diag = &decoder->diag;
AVIF_CHECKRES(avifParse(decoder));
// Walk the decoded items (if any) and harvest ispe
avifDecoderData * data = decoder->data;
for (uint32_t itemIndex = 0; itemIndex < data->meta->items.count; ++itemIndex) {
avifDecoderItem * item = data->meta->items.item[itemIndex];
if (avifDecoderItemShouldBeSkipped(item)) {
continue;
}
const avifProperty * ispeProp = avifPropertyArrayFind(&item->properties, "ispe");
if (ispeProp) {
item->width = ispeProp->u.ispe.width;
item->height = ispeProp->u.ispe.height;
if ((item->width == 0) || (item->height == 0)) {
avifDiagnosticsPrintf(data->diag, "Item ID [%u] has an invalid size [%ux%u]", item->id, item->width, item->height);
return AVIF_RESULT_BMFF_PARSE_FAILED;
}
if (avifDimensionsTooLarge(item->width, item->height, decoder->imageSizeLimit, decoder->imageDimensionLimit)) {
avifDiagnosticsPrintf(data->diag, "Item ID [%u] dimensions are too large [%ux%u]", item->id, item->width, item->height);
return AVIF_RESULT_BMFF_PARSE_FAILED;
}
} else {
const avifProperty * auxCProp = avifPropertyArrayFind(&item->properties, "auxC");
if (auxCProp && isAlphaURN(auxCProp->u.auxC.auxType)) {
if (decoder->strictFlags & AVIF_STRICT_ALPHA_ISPE_REQUIRED) {
avifDiagnosticsPrintf(data->diag,
"[Strict] Alpha auxiliary image item ID [%u] is missing a mandatory ispe property",
item->id);
return AVIF_RESULT_BMFF_PARSE_FAILED;
}
} else {
avifDiagnosticsPrintf(data->diag, "Item ID [%u] is missing a mandatory ispe property", item->id);
return AVIF_RESULT_BMFF_PARSE_FAILED;
}
}
}
return avifDecoderReset(decoder);
}
static avifResult avifCodecCreateInternal(avifCodecChoice choice, const avifTile * tile, avifDiagnostics * diag, avifCodec ** codec)
{
#if defined(AVIF_CODEC_AVM)
// AVIF_CODEC_CHOICE_AUTO leads to AVIF_CODEC_TYPE_AV1 by default. Reroute correctly.
if (choice == AVIF_CODEC_CHOICE_AUTO && tile->codecType == AVIF_CODEC_TYPE_AV2) {
choice = AVIF_CODEC_CHOICE_AVM;
}
#endif
const avifCodecType codecTypeFromChoice = avifCodecTypeFromChoice(choice, AVIF_CODEC_FLAG_CAN_DECODE);
if (codecTypeFromChoice == AVIF_CODEC_TYPE_UNKNOWN) {
avifDiagnosticsPrintf(diag,
"Tile type is %s but there is no compatible codec available to decode it",
avifGetConfigurationPropertyName(tile->codecType));
return AVIF_RESULT_NO_CODEC_AVAILABLE;
} else if (choice != AVIF_CODEC_CHOICE_AUTO && codecTypeFromChoice != tile->codecType) {
avifDiagnosticsPrintf(diag,
"Tile type is %s but incompatible %s codec was explicitly set as decoding implementation",
avifGetConfigurationPropertyName(tile->codecType),
avifCodecName(choice, AVIF_CODEC_FLAG_CAN_DECODE));
return AVIF_RESULT_DECODE_COLOR_FAILED;
}
AVIF_CHECKRES(avifCodecCreate(choice, AVIF_CODEC_FLAG_CAN_DECODE, codec));
AVIF_CHECKERR(*codec, AVIF_RESULT_OUT_OF_MEMORY);
(*codec)->diag = diag;
(*codec)->operatingPoint = tile->operatingPoint;
(*codec)->allLayers = tile->input->allLayers;
return AVIF_RESULT_OK;
}
static avifBool avifTilesCanBeDecodedWithSameCodecInstance(const avifDecoderData * data)
{
int32_t numImageBuffers = 0, numStolenImageBuffers = 0;
for (int c = 0; c < AVIF_ITEM_CATEGORY_COUNT; ++c) {
if (data->tileInfos[c].tileCount > 0) {
++numImageBuffers;
}
// The sample operations require multiple buffers for compositing so no plane is stolen
// when there is a 'sato' Sample Transform derived image item.
if (c >= AVIF_SAMPLE_TRANSFORM_MIN_CATEGORY && c <= AVIF_SAMPLE_TRANSFORM_MAX_CATEGORY && data->tileInfos[c].tileCount > 0) {
continue;
}
if (data->tileInfos[c].tileCount == 1) {
++numStolenImageBuffers;
}
}
if (numStolenImageBuffers > 0 && numImageBuffers > 1) {
// Single tile image with single tile alpha plane or gain map. In this case each tile needs its own decoder since the planes will be
// "stolen". Stealing either the color or the alpha plane (or gain map) will invalidate the other ones when decode is called the second
// (or third) time.
return AVIF_FALSE;
}
const uint8_t firstTileOperatingPoint = data->tiles.tile[0].operatingPoint;
const avifBool firstTileAllLayers = data->tiles.tile[0].input->allLayers;
for (unsigned int i = 1; i < data->tiles.count; ++i) {
const avifTile * tile = &data->tiles.tile[i];
if (tile->operatingPoint != firstTileOperatingPoint || tile->input->allLayers != firstTileAllLayers) {
return AVIF_FALSE;
}
// avifDecoderItemValidateProperties() verified during avifDecoderParse() that all tiles
// share the same coding format so no need to check for codecType equality here.
}
return AVIF_TRUE;
}
static avifResult avifDecoderCreateCodecs(avifDecoder * decoder)
{
avifDecoderData * data = decoder->data;
avifDecoderDataResetCodec(data);
if (data->source == AVIF_DECODER_SOURCE_TRACKS) {
// In this case, we will use at most two codec instances (one for the color planes and one for the alpha plane).
// Gain maps are not supported.
AVIF_CHECKRES(avifCodecCreateInternal(decoder->codecChoice, &decoder->data->tiles.tile[0], &decoder->diag, &data->codec));
data->tiles.tile[0].codec = data->codec;
if (data->tiles.count > 1) {
AVIF_CHECKRES(avifCodecCreateInternal(decoder->codecChoice, &decoder->data->tiles.tile[1], &decoder->diag, &data->codecAlpha));
data->tiles.tile[1].codec = data->codecAlpha;
}
} else {
// In this case, we will use one codec instance when there is only one tile or when all of the following conditions are
// met:
// - The image must have exactly one layer (i.e. decoder->imageCount == 1).
// - All the tiles must have the same operating point (because the codecs take operating point once at initialization
// and do not allow it to be changed later).
// - All the tiles must have the same value for allLayers (because the codecs take allLayers once at initialization
// and do not allow it to be changed later).
// - If the image has a single tile, it must not have a single tile alpha plane (in this case we will steal the planes
// from the decoder, so we cannot use the same decoder for both the color and the alpha planes).
// - All tiles have the same type (AV1 or AV2).
// - No tile buffer access after another tile was decoded (i.e. no Sample Transform compositing because it happens
// after decoding all tiles).
// Otherwise, we will use |tiles.count| decoder instances (one instance for each tile).
const avifBool canUseSingleCodecInstance =
((data->tiles.count == 1) || (decoder->imageCount == 1 && avifTilesCanBeDecodedWithSameCodecInstance(data))) &&
data->sampleTransformNumInputImageItems == 0;
if (canUseSingleCodecInstance) {
AVIF_CHECKRES(avifCodecCreateInternal(decoder->codecChoice, &decoder->data->tiles.tile[0], &decoder->diag, &data->codec));
for (unsigned int i = 0; i < decoder->data->tiles.count; ++i) {
decoder->data->tiles.tile[i].codec = data->codec;
}
} else {
for (unsigned int i = 0; i < decoder->data->tiles.count; ++i) {
avifTile * tile = &decoder->data->tiles.tile[i];
AVIF_CHECKRES(avifCodecCreateInternal(decoder->codecChoice, tile, &decoder->diag, &tile->codec));
}
}
}
return AVIF_RESULT_OK;
}
// Returns the primary color item if found, or NULL.
static avifDecoderItem * avifMetaFindColorItem(avifMeta * meta)
{
for (uint32_t itemIndex = 0; itemIndex < meta->items.count; ++itemIndex) {
avifDecoderItem * item = meta->items.item[itemIndex];
if (avifDecoderItemShouldBeSkipped(item)) {
continue;
}
if (item->id == meta->primaryItemID) {
return item;
}
}
return NULL;
}
// Returns AVIF_TRUE if item is an alpha auxiliary item of the parent color
// item.
static avifBool avifDecoderItemIsAlphaAux(const avifDecoderItem * item, uint32_t colorItemId)
{
if (item->auxForID != colorItemId)
return AVIF_FALSE;
const avifProperty * auxCProp = avifPropertyArrayFind(&item->properties, "auxC");
return auxCProp && isAlphaURN(auxCProp->u.auxC.auxType);
}
// Finds the alpha item whose parent item is colorItem and sets it in the alphaItem output parameter. Returns AVIF_RESULT_OK on
// success. Note that *alphaItem can be NULL even if the return value is AVIF_RESULT_OK. If the colorItem is a grid and the alpha
// item is represented as a set of auxl items to each color tile, then a fake item will be created and *isAlphaItemInInput will be
// set to AVIF_FALSE. In this case, the alpha item merely exists to hold the locations of the alpha tile items. The data of this
// item need not be read and the pixi property cannot be validated. Otherwise, *isAlphaItemInInput will be set to AVIF_TRUE when
// *alphaItem is not NULL.
static avifResult avifMetaFindAlphaItem(avifMeta * meta,
const avifDecoderItem * colorItem,
const avifTileInfo * colorInfo,
avifDecoderItem ** alphaItem,
avifTileInfo * alphaInfo,
avifBool * isAlphaItemInInput)
{
for (uint32_t itemIndex = 0; itemIndex < meta->items.count; ++itemIndex) {
avifDecoderItem * item = meta->items.item[itemIndex];
if (avifDecoderItemShouldBeSkipped(item)) {
continue;
}
if (avifDecoderItemIsAlphaAux(item, colorItem->id)) {
*alphaItem = item;
*isAlphaItemInInput = AVIF_TRUE;
return AVIF_RESULT_OK;
}
}
if (memcmp(colorItem->type, "grid", 4)) {
*alphaItem = NULL;
*isAlphaItemInInput = AVIF_FALSE;
return AVIF_RESULT_OK;
}
// If color item is a grid, check if there is an alpha channel which is represented as an auxl item to each color tile item.
const uint32_t tileCount = colorInfo->grid.rows * colorInfo->grid.columns;
if (tileCount == 0) {
*alphaItem = NULL;
*isAlphaItemInInput = AVIF_FALSE;
return AVIF_RESULT_OK;
}
// Keep the same 'dimg' order as it defines where each tile is located in the reconstructed image.
uint32_t * dimgIdxToAlphaItemIdx = (uint32_t *)avifAlloc(tileCount * sizeof(uint32_t));
AVIF_CHECKERR(dimgIdxToAlphaItemIdx != NULL, AVIF_RESULT_OUT_OF_MEMORY);
const uint32_t itemIndexNotSet = UINT32_MAX;
for (uint32_t dimgIdx = 0; dimgIdx < tileCount; ++dimgIdx) {
dimgIdxToAlphaItemIdx[dimgIdx] = itemIndexNotSet;
}
uint32_t alphaItemCount = 0;
for (uint32_t i = 0; i < meta->items.count; ++i) {
const avifDecoderItem * const item = meta->items.item[i];
if (item->dimgForID == colorItem->id) {
avifBool seenAlphaForCurrentItem = AVIF_FALSE;
for (uint32_t j = 0; j < meta->items.count; ++j) {
avifDecoderItem * auxlItem = meta->items.item[j];
if (avifDecoderItemIsAlphaAux(auxlItem, item->id)) {
if (seenAlphaForCurrentItem || auxlItem->dimgForID != 0 || item->dimgIdx >= tileCount ||
dimgIdxToAlphaItemIdx[item->dimgIdx] != itemIndexNotSet) {
// One of the following invalid cases:
// * Multiple items are claiming to be the alpha auxiliary of the current item.
// * Alpha auxiliary is dimg for another item.
// * There are too many items in the dimg array (also checked later in avifFillDimgIdxToItemIdxArray()).
// * There is a repetition in the dimg array (also checked later in avifFillDimgIdxToItemIdxArray()).
avifFree(dimgIdxToAlphaItemIdx);
return AVIF_RESULT_INVALID_IMAGE_GRID;
}
dimgIdxToAlphaItemIdx[item->dimgIdx] = j;
++alphaItemCount;
seenAlphaForCurrentItem = AVIF_TRUE;
}
}
if (!seenAlphaForCurrentItem) {
// No alpha auxiliary item was found for the current item. Treat this as an image without alpha.
avifFree(dimgIdxToAlphaItemIdx);
*alphaItem = NULL;
*isAlphaItemInInput = AVIF_FALSE;
return AVIF_RESULT_OK;
}
}
}
if (alphaItemCount != tileCount) {
avifFree(dimgIdxToAlphaItemIdx);
return AVIF_RESULT_INVALID_IMAGE_GRID;
}
// Find an unused ID.
avifResult result;
if (meta->items.count >= UINT32_MAX - 1) {
// In the improbable case where all IDs are used.
result = AVIF_RESULT_DECODE_ALPHA_FAILED;
} else {
uint32_t newItemID = 0;
avifBool isUsed;
do {
++newItemID;
isUsed = AVIF_FALSE;
for (uint32_t i = 0; i < meta->items.count; ++i) {
if (meta->items.item[i]->id == newItemID) {
isUsed = AVIF_TRUE;
break;
}
}
} while (isUsed && newItemID != 0);
result = avifMetaFindOrCreateItem(meta, newItemID, alphaItem); // Create new empty item.
}
if (result != AVIF_RESULT_OK) {
avifFree(dimgIdxToAlphaItemIdx);
return result;
}
memcpy((*alphaItem)->type, "grid", 4); // Make it a grid and register alpha items as its tiles.
(*alphaItem)->width = colorItem->width;
(*alphaItem)->height = colorItem->height;
for (uint32_t dimgIdx = 0; dimgIdx < tileCount; ++dimgIdx) {
if (dimgIdxToAlphaItemIdx[dimgIdx] >= meta->items.count) {
avifFree(dimgIdxToAlphaItemIdx);
AVIF_ASSERT_NOT_REACHED_OR_RETURN;
}
avifDecoderItem * alphaTileItem = meta->items.item[dimgIdxToAlphaItemIdx[dimgIdx]];
alphaTileItem->dimgForID = (*alphaItem)->id;
alphaTileItem->dimgIdx = dimgIdx;
}
avifFree(dimgIdxToAlphaItemIdx);
*isAlphaItemInInput = AVIF_FALSE;
alphaInfo->grid = colorInfo->grid;
return AVIF_RESULT_OK;
}
// If cicpSet is not NULL, the caller must set |*cicpSet| to AVIF_FALSE before
// calling this function.
// On success, this function returns AVIF_RESULT_OK and does the following:
// * If a nclx property was found in |properties|:
// - Set |*colorPrimaries|, |*transferCharacteristics|, |*matrixCoefficients|
// and |*yuvRange|.
// - If cicpSet is not NULL, set |*cicpSet| to AVIF_TRUE.
// This function fails if more than one nclx property is found in |properties|.
// The output parameters may be populated even in case of failure and must be
// ignored.
static avifResult avifReadColorNclxProperty(const avifPropertyArray * properties,
avifColorPrimaries * colorPrimaries,
avifTransferCharacteristics * transferCharacteristics,
avifMatrixCoefficients * matrixCoefficients,
avifRange * yuvRange,
avifBool * cicpSet)
{
assert(cicpSet == NULL || *cicpSet == AVIF_FALSE);
avifBool colrNCLXSeen = AVIF_FALSE;
for (uint32_t propertyIndex = 0; propertyIndex < properties->count; ++propertyIndex) {
avifProperty * prop = &properties->prop[propertyIndex];
if (!memcmp(prop->type, "colr", 4) && prop->u.colr.hasNCLX) {
if (colrNCLXSeen) {
return AVIF_RESULT_BMFF_PARSE_FAILED;
}
colrNCLXSeen = AVIF_TRUE;
if (cicpSet != NULL) {
*cicpSet = AVIF_TRUE;
}
*colorPrimaries = prop->u.colr.colorPrimaries;
*transferCharacteristics = prop->u.colr.transferCharacteristics;
*matrixCoefficients = prop->u.colr.matrixCoefficients;
*yuvRange = prop->u.colr.range;
}
}
return AVIF_RESULT_OK;
}
// On success, this function returns AVIF_RESULT_OK and does the following:
// * If a colr property was found in |properties|:
// - Read the icc data into |icc| from |io|.
// - Sets the CICP values as documented in avifReadColorNclxProperty().
// This function fails if more than one icc or nclx property is found in
// |properties|. The output parameters may be populated even in case of failure
// and must be ignored (and the |icc| object may need to be freed).
static avifResult avifReadColorProperties(avifIO * io,
const avifPropertyArray * properties,
avifRWData * icc,
avifColorPrimaries * colorPrimaries,
avifTransferCharacteristics * transferCharacteristics,
avifMatrixCoefficients * matrixCoefficients,
avifRange * yuvRange,
avifBool * cicpSet)
{
// Find and adopt all colr boxes "at most one for a given value of colour type" (HEIF 6.5.5.1, from Amendment 3)
// Accept one of each type, and bail out if more than one of a given type is provided.
avifBool colrICCSeen = AVIF_FALSE;
for (uint32_t propertyIndex = 0; propertyIndex < properties->count; ++propertyIndex) {
avifProperty * prop = &properties->prop[propertyIndex];
if (!memcmp(prop->type, "colr", 4) && prop->u.colr.hasICC) {
if (colrICCSeen) {
return AVIF_RESULT_BMFF_PARSE_FAILED;
}
avifROData iccRead;
AVIF_CHECKRES(io->read(io, 0, prop->u.colr.iccOffset, prop->u.colr.iccSize, &iccRead));
colrICCSeen = AVIF_TRUE;
AVIF_CHECKRES(avifRWDataSet(icc, iccRead.data, iccRead.size));
}
}
return avifReadColorNclxProperty(properties, colorPrimaries, transferCharacteristics, matrixCoefficients, yuvRange, cicpSet);
}
// Finds a 'tmap' (tone mapped image item) box associated with the given 'colorItem'.
// If found, fills 'toneMappedImageItem' and sets 'gainMapItemID' to the id of the gain map
// item associated with the box. Otherwise, sets 'toneMappedImageItem' to NULL.
// Returns AVIF_RESULT_OK if no errors were encountered (whether or not a tmap box was found).
// Assumes that there is a single tmap item, and not, e.g., a grid of tmap items.
// TODO(maryla): add support for files with multiple tmap items if it gets allowed by the spec.
static avifResult avifDecoderDataFindToneMappedImageItem(const avifDecoderData * data,
const avifDecoderItem * colorItem,
avifDecoderItem ** toneMappedImageItem,
uint32_t * gainMapItemID)
{
for (uint32_t itemIndex = 0; itemIndex < data->meta->items.count; ++itemIndex) {
avifDecoderItem * item = data->meta->items.item[itemIndex];
if (!item->size || item->hasUnsupportedEssentialProperty || item->thumbnailForID != 0) {
continue;
}
if (!memcmp(item->type, "tmap", 4)) {
// The tmap box should be associated (via 'iref'->'dimg') to two items:
// the first one is the base image, the second one is the gain map.
uint32_t dimgItemIDs[2] = { 0, 0 };
uint32_t numDimgItemIDs = 0;
for (uint32_t otherItemIndex = 0; otherItemIndex < data->meta->items.count; ++otherItemIndex) {
avifDecoderItem * otherItem = data->meta->items.item[otherItemIndex];
if (otherItem->dimgForID != item->id) {
continue;
}
if (otherItem->dimgIdx < 2) {
AVIF_ASSERT_OR_RETURN(dimgItemIDs[otherItem->dimgIdx] == 0);
dimgItemIDs[otherItem->dimgIdx] = otherItem->id;
}
numDimgItemIDs++;
}
// Even with numDimgItemIDs == 2, one of the ids could be 0 if there are duplicate entries in the 'dimg' box.
if (numDimgItemIDs != 2 || dimgItemIDs[0] == 0 || dimgItemIDs[1] == 0) {
avifDiagnosticsPrintf(data->diag, "box[dimg] for 'tmap' item %d must have exactly 2 entries with distinct ids", item->id);
return AVIF_RESULT_INVALID_TONE_MAPPED_IMAGE;
}
if (dimgItemIDs[0] != colorItem->id) {
continue;
}
*toneMappedImageItem = item;
*gainMapItemID = dimgItemIDs[1];
return AVIF_RESULT_OK;
}
}
*toneMappedImageItem = NULL;
*gainMapItemID = 0;
return AVIF_RESULT_OK;
}
// Returns AVIF_TRUE if the two entity ids (usually item ids) are part of an
// 'altr' group (representing entities that are alternatives of each other)
// with 'id1' appearing before 'id2' (meaning that 'id1' should be preferred).
static avifBool avifIsPreferredAlternativeTo(const avifDecoderData * data, uint32_t id1, uint32_t id2)
{
for (uint32_t i = 0; i < data->meta->entityToGroups.count; ++i) {
avifEntityToGroup * group = &data->meta->entityToGroups.groups[i];
if (memcmp(group->groupingType, "altr", 4) != 0) {
continue;
}
avifBool id1Found = AVIF_FALSE;
for (uint32_t j = 0; j < group->entityIDs.count; ++j) {
if (group->entityIDs.ids[j] == id1) {
id1Found = AVIF_TRUE;
} else if (group->entityIDs.ids[j] == id2) {
// Assume id2 is only present in one altr group, as per ISO/IEC 14496-12:2022
// Section 8.15.3.1:
// Any entity_id value shall be mapped to only one grouping of type 'altr'.
return id1Found;
}
}
}
return AVIF_FALSE;
}
// Finds a 'tmap' (tone mapped image item) box associated with the given 'colorItem',
// then finds the associated gain map image.
// If found, fills 'gainMapItem' and 'gainMapCodecType', and allocates and fills in
// decoder->image->gainMap.
// Otherwise, sets 'gainMapItem' to NULL and gainMapCodecType to AVIF_CODEC_TYPE_UNKNOWN.
// Returns AVIF_RESULT_OK if no errors were encountered (whether or not a gain map was found).
// Assumes that there is a single tmap item, and not, e.g., a grid of tmap items.
static avifResult avifDecoderFindGainMapItem(const avifDecoder * decoder,
const avifDecoderItem * colorItem,
avifDecoderItem ** gainMapItem,
avifCodecType * gainMapCodecType)
{
*gainMapItem = NULL;
*gainMapCodecType = AVIF_CODEC_TYPE_UNKNOWN;
avifDecoderData * data = decoder->data;
// Find tmap and gain map item ids.
uint32_t gainMapItemID;
avifDecoderItem * toneMappedImageItemTmp;
AVIF_CHECKRES(avifDecoderDataFindToneMappedImageItem(data, colorItem, &toneMappedImageItemTmp, &gainMapItemID));
if (!toneMappedImageItemTmp || !gainMapItemID) {
return AVIF_RESULT_OK;
}
if (!avifIsPreferredAlternativeTo(data, toneMappedImageItemTmp->id, colorItem->id)) {
return AVIF_RESULT_OK;
}
// Parse tmap item data (containing the gain map metadata).
avifROData tmapData;
AVIF_CHECKRES(avifDecoderItemRead(toneMappedImageItemTmp, decoder->io, &tmapData, 0, 0, data->diag));
// Allocate avifGainMap on the stack instead of using avifGainMapCreate() to simplify error handling.
avifGainMap gainMapTmp;
avifGainMapSetDefaults(&gainMapTmp);
const avifResult tmapParsingRes = avifParseToneMappedImageBox(&gainMapTmp, tmapData.data, tmapData.size, data->diag);
if (tmapParsingRes == AVIF_RESULT_NOT_IMPLEMENTED) {
// Unsupported gain map version. Simply ignore the gain map.
return AVIF_RESULT_OK;
}
AVIF_CHECKRES(tmapParsingRes);
avifDecoderItem * gainMapItemTmp;
AVIF_CHECKRES(avifMetaFindOrCreateItem(data->meta, gainMapItemID, &gainMapItemTmp));
if (avifDecoderItemShouldBeSkipped(gainMapItemTmp)) {
return AVIF_RESULT_NOT_IMPLEMENTED;
}
const avifResult gainMapParsingRes = avifDecoderItemReadAndParse(decoder,
gainMapItemTmp,
/*isItemInInput=*/AVIF_TRUE,
&data->tileInfos[AVIF_ITEM_GAIN_MAP].grid,
gainMapCodecType);
if (gainMapParsingRes == AVIF_RESULT_NOT_IMPLEMENTED) {
return AVIF_RESULT_OK;
}
AVIF_CHECKRES(gainMapParsingRes);
AVIF_CHECKRES(avifReadColorProperties(decoder->io,
&toneMappedImageItemTmp->properties,
&gainMapTmp.altICC,
&gainMapTmp.altColorPrimaries,
&gainMapTmp.altTransferCharacteristics,
&gainMapTmp.altMatrixCoefficients,
&gainMapTmp.altYUVRange,
/*cicpSet=*/NULL));
const avifProperty * clliProp = avifPropertyArrayFind(&toneMappedImageItemTmp->properties, "clli");
if (clliProp) {
gainMapTmp.altCLLI = clliProp->u.clli;
}
const avifProperty * pixiProp = avifPropertyArrayFind(&toneMappedImageItemTmp->properties, "pixi");
if (pixiProp) {
gainMapTmp.altPlaneCount = pixiProp->u.pixi.planeCount;
gainMapTmp.altDepth = pixiProp->u.pixi.planeDepths[0];
}
const avifProperty * ispeProp = avifPropertyArrayFind(&toneMappedImageItemTmp->properties, "ispe");
if (!ispeProp) {
// HEIF (ISO/IEC 23008-12:2022), Section 6.5.3.1:
// Every image item shall be associated with one property of this type, prior to the association
// of all transformative properties.
avifDiagnosticsPrintf(data->diag, "Box[tmap] missing mandatory ispe property");
return AVIF_RESULT_BMFF_PARSE_FAILED;
}
if (ispeProp->u.ispe.width != colorItem->width || ispeProp->u.ispe.height != colorItem->height) {
avifDiagnosticsPrintf(data->diag, "Box[tmap] ispe property width/height does not match base image");
return AVIF_RESULT_BMFF_PARSE_FAILED;
}
if (avifPropertyArrayFind(&toneMappedImageItemTmp->properties, "pasp") ||
avifPropertyArrayFind(&toneMappedImageItemTmp->properties, "clap") ||
avifPropertyArrayFind(&toneMappedImageItemTmp->properties, "irot") ||
avifPropertyArrayFind(&toneMappedImageItemTmp->properties, "imir")) {
// libavif requires the bitstream contain the same pasp, clap, irot, imir
// properties for both the base and gain map image items used as input to
// the tone-mapped derived image item. libavif also requires the tone-mapped
// derived image item itself not be associated with these properties. This is
// enforced at encoding. Other patterns are rejected at decoding.
avifDiagnosticsPrintf(data->diag,
"Box[tmap] 'pasp', 'clap', 'irot' and 'imir' properties must be associated with base and gain map items instead of 'tmap'");
return AVIF_RESULT_INVALID_TONE_MAPPED_IMAGE;
}
avifColorPrimaries colorPrimaries = AVIF_COLOR_PRIMARIES_UNSPECIFIED;
avifTransferCharacteristics transferCharacteristics = AVIF_TRANSFER_CHARACTERISTICS_UNSPECIFIED;
avifMatrixCoefficients matrixCoefficients = AVIF_MATRIX_COEFFICIENTS_UNSPECIFIED;
avifRange yuvRange = AVIF_RANGE_FULL;
avifBool cicpSet = AVIF_FALSE;
// Look for a colr nclx box. Other colr box types (e.g. ICC) are not supported.
AVIF_CHECKRES(
avifReadColorNclxProperty(&gainMapItemTmp->properties, &colorPrimaries, &transferCharacteristics, &matrixCoefficients, &yuvRange, &cicpSet));
// -- Everything is valid, do memory allocations and fill in output data. --
decoder->image->gainMap = avifGainMapCreate();
AVIF_CHECKERR(decoder->image->gainMap, AVIF_RESULT_OUT_OF_MEMORY);
*decoder->image->gainMap = gainMapTmp;
if (decoder->imageContentToDecode & AVIF_IMAGE_CONTENT_GAIN_MAP) {
decoder->image->gainMap->image = avifImageCreateEmpty();
avifImage * image = decoder->image->gainMap->image;
AVIF_CHECKERR(image, AVIF_RESULT_OUT_OF_MEMORY);
if (cicpSet) {
image->colorPrimaries = colorPrimaries;
image->transferCharacteristics = transferCharacteristics;
image->matrixCoefficients = matrixCoefficients;
image->yuvRange = yuvRange;
}
}
// Only set the output pointer after everything has been validated.
*gainMapItem = gainMapItemTmp;
return AVIF_RESULT_OK;
}
static avifResult avifDecoderCheckAlphaProperties(avifDecoder * decoder, const avifPropertyArray * alphaProperties)
{
const avifImage * image = decoder->image;
// The 'clap', 'irot' and 'imir' transformative properties should be applied to the alpha
// auxiliary image item before considering it a plane of the color image item.
// Alternatively, inequality with the transformative properties attached to the color image item
// should be treated as AVIF_RESULT_NOT_IMPLEMENTED.
// The latter is easier and is the behavior of libavif.
const avifProperty * clapProp = avifPropertyArrayFind(alphaProperties, "clap");
const avifProperty * irotProp = avifPropertyArrayFind(alphaProperties, "irot");
const avifProperty * imirProp = avifPropertyArrayFind(alphaProperties, "imir");
if (clapProp == NULL && irotProp == NULL && imirProp == NULL) {
// However, libavif up to version 1.3.0 generated images lacking transformative property
// associations with alpha auxiliary image items, so be lenient on their absence for
// backward compatibility with previously generated images.
return AVIF_RESULT_OK;
}
// HEIF (ISO/IEC 23008-12), Section 6.9.1:
// When the width or the height of the alpha plane differs from the width or the height of the
// master image, respectively, the alpha plane is resized to have the same width and height as
// those of the master image.
// There is no need to enforce specific 'ispe' values describing the alpha item because
// the alpha item must be resized to the dimensions of the associated color item.
if (!clapProp != !(image->transformFlags & AVIF_TRANSFORM_CLAP) ||
(clapProp && (clapProp->u.clap.widthN != image->clap.widthN || clapProp->u.clap.widthD != image->clap.widthD ||
clapProp->u.clap.heightN != image->clap.heightN || clapProp->u.clap.heightD != image->clap.heightD ||
clapProp->u.clap.horizOffN != image->clap.horizOffN || clapProp->u.clap.horizOffD != image->clap.horizOffD ||
clapProp->u.clap.vertOffN != image->clap.vertOffN || clapProp->u.clap.vertOffD != image->clap.vertOffD))) {
avifDiagnosticsPrintf(&decoder->diag, "Clean aperture property mismatch between alpha auxiliary image item and color item");
return AVIF_RESULT_NOT_IMPLEMENTED;
}
if (!irotProp != !(image->transformFlags & AVIF_TRANSFORM_IROT) || (irotProp && irotProp->u.irot.angle != image->irot.angle)) {
avifDiagnosticsPrintf(&decoder->diag, "Rotation property mismatch between alpha auxiliary image item and color item");
return AVIF_RESULT_NOT_IMPLEMENTED;
}
if (!imirProp != !(image->transformFlags & AVIF_TRANSFORM_IMIR) || (imirProp && imirProp->u.imir.axis != image->imir.axis)) {
avifDiagnosticsPrintf(&decoder->diag, "Mirroring property mismatch between alpha auxiliary image item and color item");
return AVIF_RESULT_NOT_IMPLEMENTED;
}
return AVIF_RESULT_OK;
}
static avifResult avifDecoderCheckGainMapProperties(avifDecoder * decoder, const avifPropertyArray * gainMapProperties)
{
const avifImage * image = decoder->image;
// libavif requires the bitstream contain the same 'pasp', 'clap', 'irot', 'imir'
// properties for both the base and gain map image items used as input to
// the tone-mapped derived image item. libavif also requires the tone-mapped
// derived image item itself not be associated with these properties. This is
// enforced at encoding. Other patterns are rejected at decoding.
const avifProperty * paspProp = avifPropertyArrayFind(gainMapProperties, "pasp");
if (!paspProp != !(image->transformFlags & AVIF_TRANSFORM_PASP) ||
(paspProp && (paspProp->u.pasp.hSpacing != image->pasp.hSpacing || paspProp->u.pasp.vSpacing != image->pasp.vSpacing))) {
avifDiagnosticsPrintf(&decoder->diag,
"Pixel aspect ratio property mismatch between input items of tone-mapping derived image item");
return AVIF_RESULT_DECODE_GAIN_MAP_FAILED;
}
const avifProperty * clapProp = avifPropertyArrayFind(gainMapProperties, "clap");
if (!clapProp != !(image->transformFlags & AVIF_TRANSFORM_CLAP) ||
(clapProp && (clapProp->u.clap.widthN != image->clap.widthN || clapProp->u.clap.widthD != image->clap.widthD ||
clapProp->u.clap.heightN != image->clap.heightN || clapProp->u.clap.heightD != image->clap.heightD ||
clapProp->u.clap.horizOffN != image->clap.horizOffN || clapProp->u.clap.horizOffD != image->clap.horizOffD ||
clapProp->u.clap.vertOffN != image->clap.vertOffN || clapProp->u.clap.vertOffD != image->clap.vertOffD))) {
avifDiagnosticsPrintf(&decoder->diag, "Clean aperture property mismatch between input items of tone-mapping derived image item");
return AVIF_RESULT_DECODE_GAIN_MAP_FAILED;
}
const avifProperty * irotProp = avifPropertyArrayFind(gainMapProperties, "irot");
if (!irotProp != !(image->transformFlags & AVIF_TRANSFORM_IROT) || (irotProp && irotProp->u.irot.angle != image->irot.angle)) {
avifDiagnosticsPrintf(&decoder->diag, "Rotation property mismatch between input items of tone-mapping derived image item");
return AVIF_RESULT_DECODE_GAIN_MAP_FAILED;
}
const avifProperty * imirProp = avifPropertyArrayFind(gainMapProperties, "imir");
if (!imirProp != !(image->transformFlags & AVIF_TRANSFORM_IMIR) || (imirProp && imirProp->u.imir.axis != image->imir.axis)) {
avifDiagnosticsPrintf(&decoder->diag, "Mirroring property mismatch between input items of tone-mapping derived image item");
return AVIF_RESULT_DECODE_GAIN_MAP_FAILED;
}
return AVIF_RESULT_OK;
}
// Finds any 'sato' Sample Transform derived image item, distinct from the primary image item,
// and in the same 'altr' group as the primary image item. Returns NULL otherwise.
static avifDecoderItem * avifDecoderDataFindSampleTransformImageItem(avifDecoderData * data)
{
for (uint32_t itemIndex = 0; itemIndex < data->meta->items.count; ++itemIndex) {
avifDecoderItem * item = data->meta->items.item[itemIndex];
if (!memcmp(item->type, "sato", 4) && item->id != data->meta->primaryItemID && item->size != 0 &&
!item->hasUnsupportedEssentialProperty && item->thumbnailForID == 0 &&
avifIsPreferredAlternativeTo(data, item->id, data->meta->primaryItemID)) {
return item;
}
}
return NULL;
}
static avifResult avifDecoderGenerateImageTiles(avifDecoder * decoder, avifTileInfo * info, avifDecoderItem * item, avifItemCategory itemCategory)
{
const uint32_t previousTileCount = decoder->data->tiles.count;
if ((info->grid.rows > 0) && (info->grid.columns > 0)) {
// The number of tiles was verified in avifDecoderItemReadAndParse().
const uint32_t numTiles = info->grid.rows * info->grid.columns;
uint32_t * dimgIdxToItemIdx = (uint32_t *)avifAlloc(numTiles * sizeof(uint32_t));
AVIF_CHECKERR(dimgIdxToItemIdx != NULL, AVIF_RESULT_OUT_OF_MEMORY);
avifResult result = avifFillDimgIdxToItemIdxArray(dimgIdxToItemIdx, numTiles, item);
if (result == AVIF_RESULT_OK) {
result = avifDecoderGenerateImageGridTiles(decoder, item, itemCategory, dimgIdxToItemIdx, numTiles);
}
avifFree(dimgIdxToItemIdx);
AVIF_CHECKRES(result);
} else {
AVIF_CHECKERR(item->size != 0, AVIF_RESULT_MISSING_IMAGE_ITEM);
const avifCodecType codecType = avifGetCodecType(item->type);
AVIF_ASSERT_OR_RETURN(codecType != AVIF_CODEC_TYPE_UNKNOWN);
avifTile * tile =
avifDecoderDataCreateTile(decoder->data, codecType, item->width, item->height, avifDecoderItemOperatingPoint(item));
AVIF_CHECKERR(tile, AVIF_RESULT_OUT_OF_MEMORY);
AVIF_CHECKRES(avifCodecDecodeInputFillFromDecoderItem(tile->input,
item,
decoder->allowProgressive,
decoder->imageCountLimit,
decoder->io->sizeHint,
&decoder->diag));
tile->input->itemCategory = itemCategory;
}
info->tileCount = decoder->data->tiles.count - previousTileCount;
return AVIF_RESULT_OK;
}
// Populates depth, yuvFormat and yuvChromaSamplePosition fields on 'image' based on data from the codec config property (e.g. "av1C").
static avifResult avifReadCodecConfigProperty(avifImage * image, const avifPropertyArray * properties, avifCodecType codecType)
{
const avifProperty * configProp = avifPropertyArrayFind(properties, avifGetConfigurationPropertyName(codecType));
if (configProp) {
image->depth = avifCodecConfigurationBoxGetDepth(&configProp->u.av1C);
if (configProp->u.av1C.monochrome) {
image->yuvFormat = AVIF_PIXEL_FORMAT_YUV400;
} else {
if (configProp->u.av1C.chromaSubsamplingX && configProp->u.av1C.chromaSubsamplingY) {
image->yuvFormat = AVIF_PIXEL_FORMAT_YUV420;
} else if (configProp->u.av1C.chromaSubsamplingX) {
image->yuvFormat = AVIF_PIXEL_FORMAT_YUV422;
} else {
image->yuvFormat = AVIF_PIXEL_FORMAT_YUV444;
}
}
image->yuvChromaSamplePosition = (avifChromaSamplePosition)configProp->u.av1C.chromaSamplePosition;
} else {
// A configuration property box is mandatory in all valid AVIF configurations. Bail out.
return AVIF_RESULT_BMFF_PARSE_FAILED;
}
return AVIF_RESULT_OK;
}
avifResult avifDecoderReset(avifDecoder * decoder)
{
avifDiagnosticsClearError(&decoder->diag);
avifDecoderData * data = decoder->data;
if (!data) {
// Nothing to reset.
return AVIF_RESULT_OK;
}
for (int c = 0; c < AVIF_ITEM_CATEGORY_COUNT; ++c) {
memset(&data->tileInfos[c].grid, 0, sizeof(data->tileInfos[c].grid));
}
avifDecoderDataClearTiles(data);
// Prepare / cleanup decoded image state
if (decoder->image) {
avifImageDestroy(decoder->image);
}
decoder->image = avifImageCreateEmpty();
AVIF_CHECKERR(decoder->image, AVIF_RESULT_OUT_OF_MEMORY);
decoder->progressiveState = AVIF_PROGRESSIVE_STATE_UNAVAILABLE;
data->cicpSet = AVIF_FALSE;
memset(&decoder->ioStats, 0, sizeof(decoder->ioStats));
// Color only or alpha only is not currently supported.
if ((decoder->imageContentToDecode & AVIF_IMAGE_CONTENT_COLOR_AND_ALPHA) != 0 &&
(decoder->imageContentToDecode & AVIF_IMAGE_CONTENT_COLOR_AND_ALPHA) != AVIF_IMAGE_CONTENT_COLOR_AND_ALPHA) {
avifDiagnosticsPrintf(&decoder->diag, "imageContentToDecode set to only color or only alpha is not supported");
return AVIF_RESULT_NOT_IMPLEMENTED;
}
// -----------------------------------------------------------------------
// Build decode input
data->sourceSampleTable = NULL; // Reset
if (decoder->requestedSource == AVIF_DECODER_SOURCE_AUTO) {
// Honor the major brand (avif or avis) if present, otherwise prefer avis (tracks) if possible.
if (!memcmp(data->majorBrand, "avis", 4)) {
data->source = AVIF_DECODER_SOURCE_TRACKS;
} else if (!memcmp(data->majorBrand, "avif", 4)) {
data->source = AVIF_DECODER_SOURCE_PRIMARY_ITEM;
} else if (data->tracks.count > 0) {
data->source = AVIF_DECODER_SOURCE_TRACKS;
} else {
data->source = AVIF_DECODER_SOURCE_PRIMARY_ITEM;
}
} else {
data->source = decoder->requestedSource;
}
avifCodecType colorCodecType = AVIF_CODEC_TYPE_UNKNOWN;
const avifPropertyArray * colorProperties = NULL;
const avifPropertyArray * alphaProperties = NULL;
const avifPropertyArray * gainMapProperties = NULL;
if (data->source == AVIF_DECODER_SOURCE_TRACKS) {
avifTrack * colorTrack = NULL;
avifTrack * alphaTrack = NULL;
// Find primary track - this probably needs some better detection
uint32_t colorTrackIndex = 0;
for (; colorTrackIndex < data->tracks.count; ++colorTrackIndex) {
avifTrack * track = &data->tracks.track[colorTrackIndex];
if (!track->sampleTable) {
continue;
}
if (!track->id) { // trak box might be missing a tkhd box inside, skip it
continue;
}
if (!track->sampleTable->chunks.count) {
continue;
}
colorCodecType = avifSampleTableGetCodecType(track->sampleTable);
if (colorCodecType == AVIF_CODEC_TYPE_UNKNOWN) {
continue;
}
if (track->auxForID != 0) {
continue;
}
// HEIF (ISO/IEC 23008-12:2022), Section 7.1:
// In order to distinguish image sequences from video, the handler type in the
// HandlerBox of the track is 'pict' to indicate an image sequence track.
// But we do not check the handler type because it may break some existing files.
// Found one!
break;
}
if (colorTrackIndex == data->tracks.count) {
avifDiagnosticsPrintf(&decoder->diag, "Failed to find AV1 color track");
return AVIF_RESULT_NO_CONTENT;
}
colorTrack = &data->tracks.track[colorTrackIndex];
colorProperties = avifSampleTableGetProperties(colorTrack->sampleTable, colorCodecType);
if (!colorProperties) {
avifDiagnosticsPrintf(&decoder->diag, "Failed to find AV1 color track's color properties");
return AVIF_RESULT_BMFF_PARSE_FAILED;
}
// Find Exif and/or XMP metadata, if any
if (colorTrack->meta) {
// See the comment above avifDecoderFindMetadata() for the explanation of using 0 here
avifResult findResult = avifDecoderFindMetadata(decoder, colorTrack->meta, decoder->image, 0);
if (findResult != AVIF_RESULT_OK) {
return findResult;
}
}
uint32_t alphaTrackIndex = 0;
avifCodecType alphaCodecType = AVIF_CODEC_TYPE_UNKNOWN;
for (; alphaTrackIndex < data->tracks.count; ++alphaTrackIndex) {
avifTrack * track = &data->tracks.track[alphaTrackIndex];
if (!track->sampleTable) {
continue;
}
if (!track->id) {
continue;
}
if (!track->sampleTable->chunks.count) {
continue;
}
alphaCodecType = avifSampleTableGetCodecType(track->sampleTable);
if (alphaCodecType == AVIF_CODEC_TYPE_UNKNOWN) {
continue;
}
const avifPropertyArray * properties = avifSampleTableGetProperties(track->sampleTable, alphaCodecType);
const avifProperty * auxiProp = properties ? avifPropertyArrayFind(properties, "auxi") : NULL;
// If auxi is present, check that it contains the alpha URN.
// If auxi is not present, assume that the track is alpha. This is for backward compatibility with
// old versions of libavif that did not write this property, see
// https://github.com/AOMediaCodec/libavif/commit/98faa17
if (auxiProp && !isAlphaURN(auxiProp->u.auxC.auxType)) {
continue;
}
// Do not check the track's handlerType. It should be "auxv" according to
// HEIF (ISO/IEC 23008-12:2022), Section 7.5.3.1, but old versions of libavif used to write
// "pict" instead. See https://github.com/AOMediaCodec/libavif/commit/65d0af9
if (track->auxForID == colorTrack->id) {
// Found it!
alphaProperties = properties;
break;
}
}
if (alphaTrackIndex != data->tracks.count) {
alphaTrack = &data->tracks.track[alphaTrackIndex];
}
const uint8_t operatingPoint = 0; // No way to set operating point via tracks
avifTile * colorTile = avifDecoderDataCreateTile(data, colorCodecType, colorTrack->width, colorTrack->height, operatingPoint);
AVIF_CHECKERR(colorTile != NULL, AVIF_RESULT_OUT_OF_MEMORY);
AVIF_CHECKRES(avifCodecDecodeInputFillFromSampleTable(colorTile->input,
colorTrack->sampleTable,
decoder->imageCountLimit,
decoder->io->sizeHint,
data->diag));
data->tileInfos[AVIF_ITEM_COLOR].tileCount = 1;
if (alphaTrack) {
avifTile * alphaTile = avifDecoderDataCreateTile(data, alphaCodecType, alphaTrack->width, alphaTrack->height, operatingPoint);
AVIF_CHECKERR(alphaTile != NULL, AVIF_RESULT_OUT_OF_MEMORY);
AVIF_CHECKRES(avifCodecDecodeInputFillFromSampleTable(alphaTile->input,
alphaTrack->sampleTable,
decoder->imageCountLimit,
decoder->io->sizeHint,
data->diag));
alphaTile->input->itemCategory = AVIF_ITEM_ALPHA;
data->tileInfos[AVIF_ITEM_ALPHA].tileCount = 1;
}
// Stash off sample table for future timing information
data->sourceSampleTable = colorTrack->sampleTable;
// Image sequence timing
decoder->imageIndex = -1;
decoder->imageCount = (int)colorTile->input->samples.count;
decoder->timescale = colorTrack->mediaTimescale;
decoder->durationInTimescales = colorTrack->mediaDuration;
if (colorTrack->mediaTimescale) {
decoder->duration = (double)decoder->durationInTimescales / (double)colorTrack->mediaTimescale;
} else {
decoder->duration = 0;
}
// If the alphaTrack->repetitionCount and colorTrack->repetitionCount are different, we will simply use the
// colorTrack's repetitionCount.
decoder->repetitionCount = colorTrack->repetitionCount;
memset(&decoder->imageTiming, 0, sizeof(decoder->imageTiming)); // to be set in avifDecoderNextImage()
decoder->image->width = colorTrack->width;
decoder->image->height = colorTrack->height;
decoder->alphaPresent = (alphaTrack != NULL);
decoder->image->alphaPremultiplied = decoder->alphaPresent && (colorTrack->premByID == alphaTrack->id);
} else {
// Create from items
if (data->meta->primaryItemID == 0) {
// A primary item is required
avifDiagnosticsPrintf(&decoder->diag, "Primary item not specified");
return AVIF_RESULT_MISSING_IMAGE_ITEM;
}
// Main item of each group category (top-level item such as grid or single tile), if any.
avifDecoderItem * mainItems[AVIF_ITEM_CATEGORY_COUNT];
avifCodecType codecType[AVIF_ITEM_CATEGORY_COUNT];
for (int c = 0; c < AVIF_ITEM_CATEGORY_COUNT; ++c) {
mainItems[c] = NULL;
codecType[c] = AVIF_CODEC_TYPE_UNKNOWN;
}
// Mandatory primary color item
mainItems[AVIF_ITEM_COLOR] = avifMetaFindColorItem(data->meta);
if (!mainItems[AVIF_ITEM_COLOR]) {
avifDiagnosticsPrintf(&decoder->diag, "Primary item not found");
return AVIF_RESULT_MISSING_IMAGE_ITEM;
}
AVIF_CHECKRES(avifDecoderItemReadAndParse(decoder,
mainItems[AVIF_ITEM_COLOR],
/*isItemInInput=*/AVIF_TRUE,
&data->tileInfos[AVIF_ITEM_COLOR].grid,
&codecType[AVIF_ITEM_COLOR]));
colorProperties = &mainItems[AVIF_ITEM_COLOR]->properties;
colorCodecType = codecType[AVIF_ITEM_COLOR];
// Optional alpha auxiliary item
avifBool isAlphaItemInInput;
AVIF_CHECKRES(avifMetaFindAlphaItem(data->meta,
mainItems[AVIF_ITEM_COLOR],
&data->tileInfos[AVIF_ITEM_COLOR],
&mainItems[AVIF_ITEM_ALPHA],
&data->tileInfos[AVIF_ITEM_ALPHA],
&isAlphaItemInInput));
if (mainItems[AVIF_ITEM_ALPHA]) {
AVIF_CHECKRES(avifDecoderItemReadAndParse(decoder,
mainItems[AVIF_ITEM_ALPHA],
isAlphaItemInInput,
&data->tileInfos[AVIF_ITEM_ALPHA].grid,
&codecType[AVIF_ITEM_ALPHA]));
}
// Section 10.2.6 of 23008-12:2024/AMD 1:2024(E):
// 'tmap' brand
// This brand enables file players to identify and decode HEIF files containing tone-map derived image
// items. When present, this brand shall be among the brands included in the compatible_brands
// array of the FileTypeBox.
//
// If the file contains a 'tmap' item but doesn't have the 'tmap' brand, it is technically invalid.
// However, we don't report any error because in order to do detect this case consistently, we would
// need to remove the early exit in avifParse() to check if a 'tmap' item might be present
// further down the file. Instead, we simply ignore tmap items in files that lack the 'tmap' brand.
if (avifBrandArrayHasBrand(&data->compatibleBrands, "tmap")) {
avifDecoderItem * gainMapItem;
avifCodecType gainMapCodecType;
AVIF_CHECKRES(avifDecoderFindGainMapItem(decoder, mainItems[AVIF_ITEM_COLOR], &gainMapItem, &gainMapCodecType));
if (gainMapItem != NULL && decoder->imageContentToDecode & AVIF_IMAGE_CONTENT_GAIN_MAP) {
mainItems[AVIF_ITEM_GAIN_MAP] = gainMapItem;
codecType[AVIF_ITEM_GAIN_MAP] = gainMapCodecType;
}
}
// AVIF_ITEM_SAMPLE_TRANSFORM (not used through mainItems because not a coded item (well grids are not coded items either but it's different)).
avifDecoderItem * const sampleTransformItem = avifDecoderDataFindSampleTransformImageItem(data);
if ((decoder->imageContentToDecode & AVIF_IMAGE_CONTENT_COLOR_AND_ALPHA) &&
(decoder->imageContentToDecode & AVIF_IMAGE_CONTENT_SAMPLE_TRANSFORMS) && sampleTransformItem != NULL) {
AVIF_ASSERT_OR_RETURN(data->sampleTransformNumInputImageItems == 0);
for (uint32_t i = 0; i < data->meta->items.count; ++i) {
avifDecoderItem * inputImageItem = data->meta->items.item[i];
if (inputImageItem->dimgForID == sampleTransformItem->id) {
++data->sampleTransformNumInputImageItems;
}
}
// Check max number of input items allowed by the format.
if (data->sampleTransformNumInputImageItems > 32) {
avifDiagnosticsPrintf(data->diag,
"Box[sato] too many input items, format allows up to 32, got %d",
data->sampleTransformNumInputImageItems);
return AVIF_RESULT_BMFF_PARSE_FAILED;
}
// Check max number of input items supported by this implementation.
AVIF_CHECKERR(data->sampleTransformNumInputImageItems <= AVIF_SAMPLE_TRANSFORM_MAX_NUM_INPUT_IMAGE_ITEMS,
AVIF_RESULT_NOT_IMPLEMENTED);
uint32_t numExtraInputImageItems = 0;
for (uint32_t i = 0; i < data->meta->items.count; ++i) {
avifDecoderItem * inputImageItem = data->meta->items.item[i];
if (inputImageItem->dimgForID != sampleTransformItem->id) {
continue;
}
if (avifDecoderItemShouldBeSkipped(inputImageItem)) {
avifDiagnosticsPrintf(data->diag, "Box[sato] input item %u is not a supported image type", inputImageItem->id);
return AVIF_RESULT_DECODE_SAMPLE_TRANSFORM_FAILED;
}
AVIF_ASSERT_OR_RETURN(inputImageItem->dimgIdx < AVIF_SAMPLE_TRANSFORM_MAX_NUM_INPUT_IMAGE_ITEMS);
avifItemCategory * category = &data->sampleTransformInputImageItems[inputImageItem->dimgIdx];
avifBool foundItem = AVIF_FALSE;
for (int c = AVIF_ITEM_COLOR; c < AVIF_ITEM_CATEGORY_COUNT; ++c) {
if (mainItems[c] && inputImageItem->id == mainItems[c]->id) {
*category = c;
AVIF_CHECKERR(*category == AVIF_ITEM_COLOR, AVIF_RESULT_NOT_IMPLEMENTED);
foundItem = AVIF_TRUE;
break;
}
}
if (!foundItem) {
AVIF_CHECKERR(numExtraInputImageItems < AVIF_SAMPLE_TRANSFORM_MAX_NUM_EXTRA_INPUT_IMAGE_ITEMS,
AVIF_RESULT_NOT_IMPLEMENTED);
*category = (avifItemCategory)(AVIF_ITEM_SAMPLE_TRANSFORM_INPUT_0_COLOR + numExtraInputImageItems);
const avifItemCategory alphaCategory =
(avifItemCategory)(AVIF_ITEM_SAMPLE_TRANSFORM_INPUT_0_ALPHA + numExtraInputImageItems);
mainItems[*category] = inputImageItem;
++numExtraInputImageItems;
AVIF_CHECKRES(avifDecoderItemReadAndParse(decoder,
inputImageItem,
/*isItemInInput=*/AVIF_TRUE,
&data->tileInfos[*category].grid,
&codecType[*category]));
// Optional alpha auxiliary item
avifBool isAlphaInputImageItemInInput = AVIF_FALSE;
AVIF_CHECKRES(avifMetaFindAlphaItem(data->meta,
mainItems[*category],
&data->tileInfos[*category],
&mainItems[alphaCategory],
&data->tileInfos[alphaCategory],
&isAlphaInputImageItemInInput));
AVIF_CHECKERR(!mainItems[alphaCategory] == !mainItems[AVIF_ITEM_ALPHA], AVIF_RESULT_NOT_IMPLEMENTED);
if (mainItems[alphaCategory] != NULL) {
AVIF_CHECKERR(isAlphaInputImageItemInInput == isAlphaItemInInput, AVIF_RESULT_NOT_IMPLEMENTED);
AVIF_CHECKERR((mainItems[*category]->premByID == mainItems[alphaCategory]->id) ==
(mainItems[AVIF_ITEM_COLOR]->premByID == mainItems[AVIF_ITEM_ALPHA]->id),
AVIF_RESULT_NOT_IMPLEMENTED);
AVIF_CHECKRES(avifDecoderItemReadAndParse(decoder,
mainItems[alphaCategory],
isAlphaInputImageItemInInput,
&data->tileInfos[alphaCategory].grid,
&codecType[alphaCategory]));
}
}
}
AVIF_ASSERT_OR_RETURN(data->meta->sampleTransformExpression.tokens == NULL);
avifROData satoData;
AVIF_CHECKRES(avifDecoderItemRead(sampleTransformItem, decoder->io, &satoData, 0, 0, data->diag));
AVIF_CHECKRES(avifParseSampleTransformImageBox(satoData.data,
satoData.size,
data->sampleTransformNumInputImageItems,
&data->meta->sampleTransformExpression,
data->diag));
AVIF_CHECKRES(avifDecoderSampleTransformItemValidateProperties(sampleTransformItem, data->diag));
const avifProperty * pixiProp = avifPropertyArrayFind(&sampleTransformItem->properties, "pixi");
AVIF_ASSERT_OR_RETURN(pixiProp != NULL);
data->meta->sampleTransformDepth = pixiProp->u.pixi.planeDepths[0];
}
// Find Exif and/or XMP metadata, if any
AVIF_CHECKRES(avifDecoderFindMetadata(decoder, data->meta, decoder->image, mainItems[AVIF_ITEM_COLOR]->id));
// Set all counts and timing to safe-but-uninteresting values
decoder->imageIndex = -1;
decoder->imageCount = 1;
decoder->imageTiming.timescale = 1;
decoder->imageTiming.pts = 0;
decoder->imageTiming.ptsInTimescales = 0;
decoder->imageTiming.duration = 1;
decoder->imageTiming.durationInTimescales = 1;
decoder->timescale = 1;
decoder->duration = 1;
decoder->durationInTimescales = 1;
for (int c = AVIF_ITEM_COLOR; c < AVIF_ITEM_CATEGORY_COUNT; ++c) {
if (!mainItems[c]) {
continue;
}
AVIF_ASSERT_OR_RETURN(c != AVIF_ITEM_SAMPLE_TRANSFORM); // See sampleTransformItem.
if (avifIsAlpha((avifItemCategory)c) && !mainItems[c]->width && !mainItems[c]->height) {
// NON-STANDARD: Alpha subimage does not have an ispe property; adopt width/height from color item
AVIF_ASSERT_OR_RETURN(!(decoder->strictFlags & AVIF_STRICT_ALPHA_ISPE_REQUIRED));
mainItems[c]->width = mainItems[AVIF_ITEM_COLOR]->width;
mainItems[c]->height = mainItems[AVIF_ITEM_COLOR]->height;
}
AVIF_CHECKRES(avifDecoderAdoptGridTileCodecTypeIfNeeded(decoder, mainItems[c], &data->tileInfos[c]));
if (c == AVIF_ITEM_COLOR || c == AVIF_ITEM_ALPHA) {
if (!(decoder->imageContentToDecode & AVIF_IMAGE_CONTENT_COLOR_AND_ALPHA)) {
continue;
}
} else if (c == AVIF_ITEM_SAMPLE_TRANSFORM_INPUT_0_COLOR || c == AVIF_ITEM_SAMPLE_TRANSFORM_INPUT_1_COLOR ||
c == AVIF_ITEM_SAMPLE_TRANSFORM_INPUT_0_ALPHA || c == AVIF_ITEM_SAMPLE_TRANSFORM_INPUT_1_ALPHA) {
AVIF_ASSERT_OR_RETURN((decoder->imageContentToDecode & AVIF_IMAGE_CONTENT_COLOR_AND_ALPHA) &&
(decoder->imageContentToDecode & AVIF_IMAGE_CONTENT_SAMPLE_TRANSFORMS));
} else {
AVIF_ASSERT_OR_RETURN(c == AVIF_ITEM_GAIN_MAP);
if (!(decoder->imageContentToDecode & AVIF_IMAGE_CONTENT_GAIN_MAP)) {
continue;
}
}
AVIF_CHECKRES(avifDecoderGenerateImageTiles(decoder, &data->tileInfos[c], mainItems[c], (avifItemCategory)c));
avifStrictFlags strictFlags = decoder->strictFlags;
if (avifIsAlpha((avifItemCategory)c) && !isAlphaItemInInput) {
// In this case, the made up grid item will not have an associated pixi property. So validate everything else
// but the pixi property.
strictFlags &= ~(avifStrictFlags)AVIF_STRICT_PIXI_REQUIRED;
}
AVIF_CHECKRES(
avifDecoderItemValidateProperties(mainItems[c], avifGetConfigurationPropertyName(codecType[c]), &decoder->diag, strictFlags));
}
if (mainItems[AVIF_ITEM_COLOR]->progressive) {
decoder->progressiveState = AVIF_PROGRESSIVE_STATE_AVAILABLE;
// data->tileInfos[AVIF_ITEM_COLOR].firstTileIndex is not yet defined but will be set to 0 a few lines below.
const avifTile * colorTile = &data->tiles.tile[0];
if (colorTile->input->samples.count > 1) {
decoder->progressiveState = AVIF_PROGRESSIVE_STATE_ACTIVE;
decoder->imageCount = (int)colorTile->input->samples.count;
}
}
decoder->image->width = mainItems[AVIF_ITEM_COLOR]->width;
decoder->image->height = mainItems[AVIF_ITEM_COLOR]->height;
decoder->alphaPresent = (mainItems[AVIF_ITEM_ALPHA] != NULL);
decoder->image->alphaPremultiplied = decoder->alphaPresent &&
(mainItems[AVIF_ITEM_COLOR]->premByID == mainItems[AVIF_ITEM_ALPHA]->id);
if (mainItems[AVIF_ITEM_ALPHA]) {
alphaProperties = &mainItems[AVIF_ITEM_ALPHA]->properties;
}
if (mainItems[AVIF_ITEM_GAIN_MAP]) {
AVIF_ASSERT_OR_RETURN(decoder->image->gainMap && decoder->image->gainMap->image);
decoder->image->gainMap->image->width = mainItems[AVIF_ITEM_GAIN_MAP]->width;
decoder->image->gainMap->image->height = mainItems[AVIF_ITEM_GAIN_MAP]->height;
// Must be called after avifDecoderAdoptGridTileCodecType() which among other things copies the
// codec config property from the first tile of a grid to the grid item (when grids are used).
AVIF_CHECKRES(avifReadCodecConfigProperty(decoder->image->gainMap->image,
&mainItems[AVIF_ITEM_GAIN_MAP]->properties,
codecType[AVIF_ITEM_GAIN_MAP]));
gainMapProperties = &mainItems[AVIF_ITEM_GAIN_MAP]->properties;
}
}
uint32_t firstTileIndex = 0;
for (int c = 0; c < AVIF_ITEM_CATEGORY_COUNT; ++c) {
data->tileInfos[c].firstTileIndex = firstTileIndex;
firstTileIndex += data->tileInfos[c].tileCount;
}
// Sanity check tiles
for (uint32_t tileIndex = 0; tileIndex < data->tiles.count; ++tileIndex) {
avifTile * tile = &data->tiles.tile[tileIndex];
for (uint32_t sampleIndex = 0; sampleIndex < tile->input->samples.count; ++sampleIndex) {
avifDecodeSample * sample = &tile->input->samples.sample[sampleIndex];
if (!sample->size) {
// Every sample must have some data
return AVIF_RESULT_BMFF_PARSE_FAILED;
}
if (tile->input->itemCategory == AVIF_ITEM_COLOR) {
decoder->ioStats.colorOBUSize += sample->size;
} else if (tile->input->itemCategory == AVIF_ITEM_ALPHA) {
decoder->ioStats.alphaOBUSize += sample->size;
}
}
}
AVIF_CHECKRES(avifReadColorProperties(decoder->io,
colorProperties,
&decoder->image->icc,
&decoder->image->colorPrimaries,
&decoder->image->transferCharacteristics,
&decoder->image->matrixCoefficients,
&decoder->image->yuvRange,
&data->cicpSet));
const avifProperty * clliProp = avifPropertyArrayFind(colorProperties, "clli");
if (clliProp) {
decoder->image->clli = clliProp->u.clli;
}
// Transformations
const avifProperty * paspProp = avifPropertyArrayFind(colorProperties, "pasp");
if (paspProp) {
decoder->image->transformFlags |= AVIF_TRANSFORM_PASP;
decoder->image->pasp = paspProp->u.pasp;
}
const avifProperty * clapProp = avifPropertyArrayFind(colorProperties, "clap");
if (clapProp) {
decoder->image->transformFlags |= AVIF_TRANSFORM_CLAP;
decoder->image->clap = clapProp->u.clap;
}
const avifProperty * irotProp = avifPropertyArrayFind(colorProperties, "irot");
if (irotProp) {
decoder->image->transformFlags |= AVIF_TRANSFORM_IROT;
decoder->image->irot = irotProp->u.irot;
}
const avifProperty * imirProp = avifPropertyArrayFind(colorProperties, "imir");
if (imirProp) {
decoder->image->transformFlags |= AVIF_TRANSFORM_IMIR;
decoder->image->imir = imirProp->u.imir;
}
if (alphaProperties) {
AVIF_CHECKRES(avifDecoderCheckAlphaProperties(decoder, alphaProperties));
}
if (gainMapProperties) {
AVIF_CHECKRES(avifDecoderCheckGainMapProperties(decoder, gainMapProperties));
}
if (!data->cicpSet && (data->tiles.count > 0)) {
avifTile * firstTile = &data->tiles.tile[0];
if (firstTile->input->samples.count > 0) {
avifDecodeSample * sample = &firstTile->input->samples.sample[0];
// Harvest CICP from the AV1's sequence header, which should be very close to the front
// of the first sample. Read in successively larger chunks until we successfully parse the sequence.
static const size_t searchSampleChunkIncrement = 64;
static const size_t searchSampleSizeMax = 4096;
size_t searchSampleSize = 0;
do {
searchSampleSize += searchSampleChunkIncrement;
if (searchSampleSize > sample->size) {
searchSampleSize = sample->size;
}
avifResult prepareResult = avifDecoderPrepareSample(decoder, sample, searchSampleSize);
if (prepareResult != AVIF_RESULT_OK) {
return prepareResult;
}
avifSequenceHeader sequenceHeader;
if (avifSequenceHeaderParse(&sequenceHeader, &sample->data, firstTile->codecType)) {
data->cicpSet = AVIF_TRUE;
decoder->image->colorPrimaries = sequenceHeader.colorPrimaries;
decoder->image->transferCharacteristics = sequenceHeader.transferCharacteristics;
decoder->image->matrixCoefficients = sequenceHeader.matrixCoefficients;
decoder->image->yuvRange = sequenceHeader.range;
break;
}
} while (searchSampleSize != sample->size && searchSampleSize < searchSampleSizeMax);
}
}
AVIF_CHECKRES(avifReadCodecConfigProperty(decoder->image, colorProperties, colorCodecType));
if (decoder->data->meta->sampleTransformExpression.count > 0) {
AVIF_ASSERT_OR_RETURN(decoder->data->meta->sampleTransformDepth != 0);
decoder->image->depth = decoder->data->meta->sampleTransformDepth;
}
// Expose as raw bytes all other properties that libavif does not care about.
for (size_t i = 0; i < colorProperties->count; ++i) {
const avifProperty * property = &colorProperties->prop[i];
if (property->isOpaque) {
AVIF_CHECKRES(avifImagePushProperty(decoder->image,
property->type,
property->u.opaque.usertype,
property->u.opaque.boxPayload.data,
property->u.opaque.boxPayload.size));
}
}
if (gainMapProperties) {
for (size_t i = 0; i < gainMapProperties->count; ++i) {
const avifProperty * property = &gainMapProperties->prop[i];
if (property->isOpaque) {
AVIF_CHECKRES(avifImagePushProperty(decoder->image->gainMap->image,
property->type,
property->u.opaque.usertype,
property->u.opaque.boxPayload.data,
property->u.opaque.boxPayload.size));
}
}
}
return AVIF_RESULT_OK;
}
static avifResult avifDecoderPrepareTiles(avifDecoder * decoder, uint32_t nextImageIndex, const avifTileInfo * info)
{
for (unsigned int tileIndex = info->decodedTileCount; tileIndex < info->tileCount; ++tileIndex) {
avifTile * tile = &decoder->data->tiles.tile[info->firstTileIndex + tileIndex];
if (nextImageIndex >= tile->input->samples.count) {
return AVIF_RESULT_NO_IMAGES_REMAINING;
}
avifDecodeSample * sample = &tile->input->samples.sample[nextImageIndex];
avifResult prepareResult = avifDecoderPrepareSample(decoder, sample, 0);
if (prepareResult != AVIF_RESULT_OK) {
return prepareResult;
}
}
return AVIF_RESULT_OK;
}
static avifResult avifImageLimitedToFullAlpha(avifImage * image)
{
if (image->imageOwnsAlphaPlane) {
return AVIF_RESULT_NOT_IMPLEMENTED;
}
const uint8_t * alphaPlane = image->alphaPlane;
const uint32_t alphaRowBytes = image->alphaRowBytes;
// We cannot do the range conversion in place since it will modify the
// codec's internal frame buffers. Allocate memory for the conversion.
image->alphaPlane = NULL;
image->alphaRowBytes = 0;
const avifResult allocationResult = avifImageAllocatePlanes(image, AVIF_PLANES_A);
if (allocationResult != AVIF_RESULT_OK) {
return allocationResult;
}
if (image->depth > 8) {
for (uint32_t j = 0; j < image->height; ++j) {
const uint8_t * srcRow = &alphaPlane[(size_t)j * alphaRowBytes];
uint8_t * dstRow = &image->alphaPlane[(size_t)j * image->alphaRowBytes];
for (uint32_t i = 0; i < image->width; ++i) {
int srcAlpha = *((const uint16_t *)&srcRow[i * 2]);
int dstAlpha = avifLimitedToFullY(image->depth, srcAlpha);
*((uint16_t *)&dstRow[i * 2]) = (uint16_t)dstAlpha;
}
}
} else {
for (uint32_t j = 0; j < image->height; ++j) {
const uint8_t * srcRow = &alphaPlane[(size_t)j * alphaRowBytes];
uint8_t * dstRow = &image->alphaPlane[(size_t)j * image->alphaRowBytes];
for (uint32_t i = 0; i < image->width; ++i) {
int srcAlpha = srcRow[i];
int dstAlpha = avifLimitedToFullY(image->depth, srcAlpha);
dstRow[i] = (uint8_t)dstAlpha;
}
}
}
return AVIF_RESULT_OK;
}
static avifResult avifGetErrorForItemCategory(avifItemCategory itemCategory)
{
if (itemCategory == AVIF_ITEM_GAIN_MAP) {
return AVIF_RESULT_DECODE_GAIN_MAP_FAILED;
}
if (itemCategory >= AVIF_SAMPLE_TRANSFORM_MIN_CATEGORY && itemCategory <= AVIF_SAMPLE_TRANSFORM_MAX_CATEGORY) {
return AVIF_RESULT_DECODE_SAMPLE_TRANSFORM_FAILED;
}
return avifIsAlpha(itemCategory) ? AVIF_RESULT_DECODE_ALPHA_FAILED : AVIF_RESULT_DECODE_COLOR_FAILED;
}
static avifResult avifDecoderDecodeTiles(avifDecoder * decoder, uint32_t nextImageIndex, avifTileInfo * info)
{
const unsigned int oldDecodedTileCount = info->decodedTileCount;
for (unsigned int tileIndex = oldDecodedTileCount; tileIndex < info->tileCount; ++tileIndex) {
avifTile * tile = &decoder->data->tiles.tile[info->firstTileIndex + tileIndex];
const avifDecodeSample * sample = &tile->input->samples.sample[nextImageIndex];
if (sample->data.size < sample->size) {
AVIF_ASSERT_OR_RETURN(decoder->allowIncremental);
// Data is missing but there is no error yet. Output available pixel rows.
return AVIF_RESULT_OK;
}
avifBool isLimitedRangeAlpha = AVIF_FALSE;
tile->codec->maxThreads = decoder->maxThreads;
tile->codec->imageSizeLimit = decoder->imageSizeLimit;
tile->codec->imageDimensionLimit = decoder->imageDimensionLimit;
if (!tile->codec->getNextImage(tile->codec, sample, avifIsAlpha(tile->input->itemCategory), &isLimitedRangeAlpha, tile->image)) {
avifDiagnosticsPrintf(&decoder->diag, "tile->codec->getNextImage() failed");
return avifGetErrorForItemCategory(tile->input->itemCategory);
}
// Section 2.3.4 of AV1 Codec ISO Media File Format Binding v1.2.0 says:
// the full_range_flag in the colr box shall match the color_range
// flag in the Sequence Header OBU.
// See https://aomediacodec.github.io/av1-isobmff/v1.2.0.html#av1codecconfigurationbox-semantics.
// If a 'colr' box of colour_type 'nclx' was parsed, a mismatch between
// the 'colr' decoder->image->yuvRange and the AV1 OBU
// tile->image->yuvRange should be treated as an error.
// However codec_svt.c was not encoding the color_range field for
// multiple years, so there probably are files in the wild that will
// fail decoding if this is enforced. Thus this pattern is allowed.
// Section 12.1.5.1 of ISO 14496-12 (ISOBMFF) says:
// If colour information is supplied in both this [colr] box, and also
// in the video bitstream, this box takes precedence, and over-rides
// the information in the bitstream.
// So decoder->image->yuvRange is kept because it was either the 'colr'
// value set when the 'colr' box was parsed, or it was the AV1 OBU value
// extracted from the sequence header OBU of the first tile of the first
// frame (if no 'colr' box of colour_type 'nclx' was found).
// Alpha plane with limited range is not allowed by the latest revision
// of the specification. However, it was allowed in version 1.0.0 of the
// specification. To allow such files, simply convert the alpha plane to
// full range.
if (avifIsAlpha(tile->input->itemCategory) && isLimitedRangeAlpha) {
avifResult result = avifImageLimitedToFullAlpha(tile->image);
if (result != AVIF_RESULT_OK) {
avifDiagnosticsPrintf(&decoder->diag, "avifImageLimitedToFullAlpha failed");
return result;
}
}
// Scale the decoded image so that it corresponds to this tile's output dimensions
if ((tile->width != tile->image->width) || (tile->height != tile->image->height)) {
if (avifImageScaleWithLimit(tile->image,
tile->width,
tile->height,
decoder->imageSizeLimit,
decoder->imageDimensionLimit,
&decoder->diag) != AVIF_RESULT_OK) {
return avifGetErrorForItemCategory(tile->input->itemCategory);
}
}
++info->decodedTileCount;
const avifBool isGrid = (info->grid.rows > 0) && (info->grid.columns > 0);
avifBool stealPlanes = !isGrid;
if (decoder->data->meta->sampleTransformExpression.count > 0) {
// Keep everything as a copy for now.
stealPlanes = AVIF_FALSE;
}
if (tile->input->itemCategory >= AVIF_SAMPLE_TRANSFORM_MIN_CATEGORY &&
tile->input->itemCategory <= AVIF_SAMPLE_TRANSFORM_MAX_CATEGORY) {
// Keep Sample Transform input image item samples in tiles.
// The expression will be applied in avifDecoderNextImage() below instead, once all the tiles are available.
continue;
}
if (!stealPlanes) {
avifImage * dstImage = decoder->image;
if (tile->input->itemCategory == AVIF_ITEM_GAIN_MAP) {
AVIF_ASSERT_OR_RETURN(dstImage->gainMap && dstImage->gainMap->image);
dstImage = dstImage->gainMap->image;
}
if (tileIndex == 0) {
AVIF_CHECKRES(avifDecoderDataAllocateImagePlanes(decoder->data, info, dstImage, &decoder->data->cicpSet));
}
AVIF_CHECKRES(avifDecoderDataCopyTileToImage(decoder->data, info, dstImage, tile, tileIndex));
} else {
AVIF_ASSERT_OR_RETURN(info->tileCount == 1);
AVIF_ASSERT_OR_RETURN(tileIndex == 0);
avifImage * src = tile->image;
if (tile->input->itemCategory == AVIF_ITEM_GAIN_MAP) {
AVIF_ASSERT_OR_RETURN(decoder->image->gainMap && decoder->image->gainMap->image);
decoder->image->gainMap->image->width = src->width;
decoder->image->gainMap->image->height = src->height;
decoder->image->gainMap->image->depth = src->depth;
} else {
if ((decoder->image->width != src->width) || (decoder->image->height != src->height) ||
(decoder->image->depth != src->depth)) {
if (avifIsAlpha(tile->input->itemCategory)) {
avifDiagnosticsPrintf(&decoder->diag,
"The color image item does not match the alpha image item in width, height, or bit depth");
return AVIF_RESULT_DECODE_ALPHA_FAILED;
}
avifImageFreePlanes(decoder->image, AVIF_PLANES_ALL);
decoder->image->width = src->width;
decoder->image->height = src->height;
decoder->image->depth = src->depth;
}
}
if (avifIsAlpha(tile->input->itemCategory)) {
avifImageStealPlanes(decoder->image, src, AVIF_PLANES_A);
} else if (tile->input->itemCategory == AVIF_ITEM_GAIN_MAP) {
AVIF_ASSERT_OR_RETURN(decoder->image->gainMap && decoder->image->gainMap->image);
avifImageStealPlanes(decoder->image->gainMap->image, src, AVIF_PLANES_YUV);
} else { // AVIF_ITEM_COLOR
avifImageStealPlanes(decoder->image, src, AVIF_PLANES_YUV);
}
}
}
return AVIF_RESULT_OK;
}
// Returns AVIF_FALSE if there is currently a partially decoded frame.
static avifBool avifDecoderDataFrameFullyDecoded(const avifDecoderData * data)
{
for (int c = 0; c < AVIF_ITEM_CATEGORY_COUNT; ++c) {
if (data->tileInfos[c].decodedTileCount != data->tileInfos[c].tileCount) {
return AVIF_FALSE;
}
}
return AVIF_TRUE;
}
// Composites hidden image items and/or the primary image item into the dstImage.
// Tiles are aggregated into temporary buffers (reconstructedInputImages)
// covering the whole dstImage dimensions in case of grids.
// Non-null elements of reconstructedInputImages must be destroyed after calling this function.
static avifResult avifDecoderApplySampleTransformForPlanesImpl(const avifDecoder * decoder,
avifPlanesFlag planes,
avifImage * dstImage,
avifImage * reconstructedInputImages[AVIF_SAMPLE_TRANSFORM_MAX_NUM_INPUT_IMAGE_ITEMS])
{
AVIF_ASSERT_OR_RETURN(decoder->data->sampleTransformNumInputImageItems != 0);
AVIF_ASSERT_OR_RETURN(decoder->data->sampleTransformNumInputImageItems <= AVIF_SAMPLE_TRANSFORM_MAX_NUM_INPUT_IMAGE_ITEMS);
const avifImage * inputImages[AVIF_SAMPLE_TRANSFORM_MAX_NUM_INPUT_IMAGE_ITEMS];
for (uint32_t i = 0; i < decoder->data->sampleTransformNumInputImageItems; ++i) {
avifItemCategory category = decoder->data->sampleTransformInputImageItems[i];
if (category == AVIF_ITEM_COLOR) {
// If the primary image item was a grid, it was already aggregated
// into this single output buffer in avifDecoderDecodeTiles().
inputImages[i] = decoder->image;
} else {
AVIF_ASSERT_OR_RETURN(category >= AVIF_ITEM_SAMPLE_TRANSFORM_INPUT_0_COLOR &&
category < AVIF_ITEM_SAMPLE_TRANSFORM_INPUT_0_COLOR +
AVIF_SAMPLE_TRANSFORM_MAX_NUM_EXTRA_INPUT_IMAGE_ITEMS);
if (planes == AVIF_PLANES_A) {
category += AVIF_SAMPLE_TRANSFORM_MAX_NUM_EXTRA_INPUT_IMAGE_ITEMS;
}
const avifTileInfo * info = &decoder->data->tileInfos[category];
AVIF_ASSERT_OR_RETURN(info != NULL);
const avifTile * firstTile = &decoder->data->tiles.tile[info->firstTileIndex];
AVIF_ASSERT_OR_RETURN(firstTile != NULL && firstTile->image != NULL);
if (info->tileCount == 1) {
inputImages[i] = firstTile->image;
} else {
// Combine the tiles into a single buffer used as one of the input images in avifImageApplyExpression().
reconstructedInputImages[i] = avifImageCreateEmpty();
AVIF_CHECKERR(reconstructedInputImages[i] != NULL, AVIF_RESULT_OUT_OF_MEMORY);
avifImageCopyNoAlloc(reconstructedInputImages[i], firstTile->image);
reconstructedInputImages[i]->width = decoder->image->width;
reconstructedInputImages[i]->height = decoder->image->height;
avifBool cicpSet = AVIF_TRUE;
AVIF_CHECKRES(avifDecoderDataAllocateImagePlanes(decoder->data, info, reconstructedInputImages[i], &cicpSet));
for (unsigned int tileIndex = 0; tileIndex < info->tileCount; ++tileIndex) {
const avifTile * tile = firstTile + tileIndex;
AVIF_CHECKRES(avifDecoderDataCopyTileToImage(decoder->data, info, reconstructedInputImages[i], tile, tileIndex));
}
inputImages[i] = reconstructedInputImages[i];
}
}
}
AVIF_CHECKRES(avifImageApplyExpression(dstImage,
AVIF_SAMPLE_TRANSFORM_BIT_DEPTH_32,
&decoder->data->meta->sampleTransformExpression,
decoder->data->sampleTransformNumInputImageItems,
inputImages,
planes));
return AVIF_RESULT_OK;
}
// Intermediate function used to safely destroy temporary buffers even in case of error.
static avifResult avifDecoderApplySampleTransformForPlanes(const avifDecoder * decoder, avifPlanesFlag planes, avifImage * dstImage)
{
avifImage * toDestroy[AVIF_SAMPLE_TRANSFORM_MAX_NUM_INPUT_IMAGE_ITEMS] = { NULL };
const avifResult result = avifDecoderApplySampleTransformForPlanesImpl(decoder, planes, dstImage, toDestroy);
for (uint32_t i = 0; i < AVIF_SAMPLE_TRANSFORM_MAX_NUM_INPUT_IMAGE_ITEMS; ++i) {
if (toDestroy[i] != NULL) {
avifImageDestroy(toDestroy[i]);
}
}
return result;
}
static avifResult avifDecoderApplySampleTransform(const avifDecoder * decoder, avifImage * dstImage)
{
if (dstImage->depth != decoder->data->meta->sampleTransformDepth) {
AVIF_ASSERT_OR_RETURN(dstImage->yuvPlanes[0] != NULL);
AVIF_ASSERT_OR_RETURN(dstImage->imageOwnsYUVPlanes);
// Use a temporary buffer because dstImage may point to decoder->image, which could be an input image.
avifImage * dstImageWithCorrectDepth =
avifImageCreate(dstImage->width, dstImage->height, decoder->data->meta->sampleTransformDepth, dstImage->yuvFormat);
AVIF_CHECKERR(dstImageWithCorrectDepth != NULL, AVIF_RESULT_OUT_OF_MEMORY);
dstImageWithCorrectDepth->yuvRange = dstImage->yuvRange;
avifResult result =
avifImageAllocatePlanes(dstImageWithCorrectDepth, dstImage->alphaPlane != NULL ? AVIF_PLANES_ALL : AVIF_PLANES_YUV);
if (result == AVIF_RESULT_OK) {
result = avifDecoderApplySampleTransform(decoder, dstImageWithCorrectDepth);
if (result == AVIF_RESULT_OK) {
// Keep the same dstImage object rather than swapping decoder->image, in case the user already accessed it.
avifImageFreePlanes(dstImage, AVIF_PLANES_ALL);
dstImage->depth = dstImageWithCorrectDepth->depth;
avifImageStealPlanes(dstImage, dstImageWithCorrectDepth, AVIF_PLANES_ALL);
}
}
avifImageDestroy(dstImageWithCorrectDepth);
return result;
}
AVIF_CHECKRES(avifDecoderApplySampleTransformForPlanes(decoder, AVIF_PLANES_YUV, dstImage));
if (decoder->alphaPresent) {
AVIF_CHECKRES(avifDecoderApplySampleTransformForPlanes(decoder, AVIF_PLANES_A, dstImage));
}
return AVIF_RESULT_OK;
}
avifResult avifDecoderNextImage(avifDecoder * decoder)
{
avifDiagnosticsClearError(&decoder->diag);
if (!decoder->data || decoder->data->tiles.count == 0) {
// Nothing has been parsed yet
return AVIF_RESULT_NO_CONTENT;
}
if (!decoder->io || !decoder->io->read) {
return AVIF_RESULT_IO_NOT_SET;
}
if (avifDecoderDataFrameFullyDecoded(decoder->data)) {
// A frame was decoded during the last avifDecoderNextImage() call.
for (int c = 0; c < AVIF_ITEM_CATEGORY_COUNT; ++c) {
decoder->data->tileInfos[c].decodedTileCount = 0;
}
}
AVIF_ASSERT_OR_RETURN(decoder->data->tiles.count == (decoder->data->tileInfos[AVIF_ITEM_CATEGORY_COUNT - 1].firstTileIndex +
decoder->data->tileInfos[AVIF_ITEM_CATEGORY_COUNT - 1].tileCount));
const uint32_t nextImageIndex = (uint32_t)(decoder->imageIndex + 1);
// Ensure that we have created the codecs before proceeding with the decoding.
if (!decoder->data->tiles.tile[0].codec) {
AVIF_CHECKRES(avifDecoderCreateCodecs(decoder));
}
// Acquire all sample data for the current image first, allowing for any read call to bail out
// with AVIF_RESULT_WAITING_ON_IO harmlessly / idempotently, unless decoder->allowIncremental.
avifResult prepareTileResult[AVIF_ITEM_CATEGORY_COUNT];
for (int c = 0; c < AVIF_ITEM_CATEGORY_COUNT; ++c) {
prepareTileResult[c] = avifDecoderPrepareTiles(decoder, nextImageIndex, &decoder->data->tileInfos[c]);
if (!decoder->allowIncremental || (prepareTileResult[c] != AVIF_RESULT_WAITING_ON_IO)) {
AVIF_CHECKRES(prepareTileResult[c]);
}
}
// Decode all available color tiles now, then all available alpha tiles, then all available bit
// depth extension tiles. The order of appearance of the tiles in the bitstream is left to the
// encoder's choice, and decoding as many as possible of each category in parallel is beneficial
// for incremental decoding, as pixel rows need all channels to be decoded before being
// accessible to the user.
for (int c = 0; c < AVIF_ITEM_CATEGORY_COUNT; ++c) {
AVIF_CHECKRES(avifDecoderDecodeTiles(decoder, nextImageIndex, &decoder->data->tileInfos[c]));
}
if (!avifDecoderDataFrameFullyDecoded(decoder->data)) {
AVIF_ASSERT_OR_RETURN(decoder->allowIncremental);
// The image is not completely decoded. There should be no error unrelated to missing bytes,
// and at least some missing bytes.
avifResult firstNonOkResult = AVIF_RESULT_OK;
for (int c = 0; c < AVIF_ITEM_CATEGORY_COUNT; ++c) {
AVIF_ASSERT_OR_RETURN(prepareTileResult[c] == AVIF_RESULT_OK || prepareTileResult[c] == AVIF_RESULT_WAITING_ON_IO);
if (firstNonOkResult == AVIF_RESULT_OK) {
firstNonOkResult = prepareTileResult[c];
}
}
AVIF_ASSERT_OR_RETURN(firstNonOkResult != AVIF_RESULT_OK);
// Return the "not enough bytes" status now instead of moving on to the next frame.
return AVIF_RESULT_WAITING_ON_IO;
}
for (int c = 0; c < AVIF_ITEM_CATEGORY_COUNT; ++c) {
AVIF_ASSERT_OR_RETURN(prepareTileResult[c] == AVIF_RESULT_OK);
}
// If decoder->data->tileInfos[AVIF_ITEM_COLOR].tileCount == 0, it means
// decoder->imageContentToDecode & AVIF_IMAGE_CONTENT_COLOR_AND_ALPHA was equal to 0.
// Only apply Sample Transforms if there is a color item to apply it onto.
if (decoder->data->tileInfos[AVIF_ITEM_COLOR].tileCount != 0 && decoder->data->meta->sampleTransformExpression.count > 0) {
AVIF_CHECKRES(avifDecoderApplySampleTransform(decoder, decoder->image));
}
// Only advance decoder->imageIndex once the image is completely decoded, so that
// avifDecoderNthImage(decoder, decoder->imageIndex + 1) is equivalent to avifDecoderNextImage(decoder)
// if the previous call to avifDecoderNextImage() returned AVIF_RESULT_WAITING_ON_IO.
decoder->imageIndex = (int)nextImageIndex;
// The decoded tile counts will be reset to 0 the next time avifDecoderNextImage() is called,
// for avifDecoderDecodedRowCount() to work until then.
if (decoder->data->sourceSampleTable) {
// Decoding from a track! Provide timing information.
avifResult timingResult = avifDecoderNthImageTiming(decoder, decoder->imageIndex, &decoder->imageTiming);
if (timingResult != AVIF_RESULT_OK) {
return timingResult;
}
}
return AVIF_RESULT_OK;
}
avifResult avifDecoderNthImageTiming(const avifDecoder * decoder, uint32_t frameIndex, avifImageTiming * outTiming)
{
if (!decoder->data) {
// Nothing has been parsed yet
return AVIF_RESULT_NO_CONTENT;
}
if ((frameIndex > INT_MAX) || ((int)frameIndex >= decoder->imageCount)) {
// Impossible index
return AVIF_RESULT_NO_IMAGES_REMAINING;
}
if (!decoder->data->sourceSampleTable) {
// There isn't any real timing associated with this decode, so
// just hand back the defaults chosen in avifDecoderReset().
*outTiming = decoder->imageTiming;
return AVIF_RESULT_OK;
}
outTiming->timescale = decoder->timescale;
outTiming->ptsInTimescales = 0;
for (uint32_t imageIndex = 0; imageIndex < frameIndex; ++imageIndex) {
outTiming->ptsInTimescales += avifSampleTableGetImageDelta(decoder->data->sourceSampleTable, imageIndex);
}
outTiming->durationInTimescales = avifSampleTableGetImageDelta(decoder->data->sourceSampleTable, frameIndex);
if (outTiming->timescale > 0) {
outTiming->pts = (double)outTiming->ptsInTimescales / (double)outTiming->timescale;
outTiming->duration = (double)outTiming->durationInTimescales / (double)outTiming->timescale;
} else {
outTiming->pts = 0.0;
outTiming->duration = 0.0;
}
return AVIF_RESULT_OK;
}
avifResult avifDecoderNthImage(avifDecoder * decoder, uint32_t frameIndex)
{
avifDiagnosticsClearError(&decoder->diag);
if (!decoder->data) {
// Nothing has been parsed yet
return AVIF_RESULT_NO_CONTENT;
}
if ((frameIndex > INT_MAX) || ((int)frameIndex >= decoder->imageCount)) {
// Impossible index
return AVIF_RESULT_NO_IMAGES_REMAINING;
}
int requestedIndex = (int)frameIndex;
if (requestedIndex == (decoder->imageIndex + 1)) {
// It's just the next image (already partially decoded or not at all), nothing special here
return avifDecoderNextImage(decoder);
}
if (requestedIndex == decoder->imageIndex) {
if (avifDecoderDataFrameFullyDecoded(decoder->data)) {
// The current fully decoded image (decoder->imageIndex) is requested, nothing to do
return AVIF_RESULT_OK;
}
// The next image (decoder->imageIndex + 1) is partially decoded but
// the previous image (decoder->imageIndex) is requested.
// Fall through to resetting the decoder data and start decoding from
// the nearest key frame.
}
int nearestKeyFrame = (int)avifDecoderNearestKeyframe(decoder, frameIndex);
if ((nearestKeyFrame > (decoder->imageIndex + 1)) || (requestedIndex <= decoder->imageIndex)) {
// If we get here, we need to start decoding from the nearest key frame.
// So discard the unused decoder state and its previous frames. This
// will force the setup of new AV1 decoder (avifCodec) instances in
// avifDecoderNextImage().
decoder->imageIndex = nearestKeyFrame - 1; // prepare to read nearest keyframe
avifDecoderDataResetCodec(decoder->data);
}
for (;;) {
avifResult result = avifDecoderNextImage(decoder);
if (result != AVIF_RESULT_OK) {
return result;
}
if (requestedIndex == decoder->imageIndex) {
break;
}
}
return AVIF_RESULT_OK;
}
avifBool avifDecoderIsKeyframe(const avifDecoder * decoder, uint32_t frameIndex)
{
if (!decoder->data || (decoder->data->tiles.count == 0)) {
// Nothing has been parsed yet
return AVIF_FALSE;
}
// *All* tiles for the requested frameIndex must be keyframes in order for
// avifDecoderIsKeyframe() to return true, otherwise we may seek to a frame in which the color
// planes are a keyframe but the alpha plane isn't a keyframe, which will cause an alpha plane
// decode failure.
for (unsigned int i = 0; i < decoder->data->tiles.count; ++i) {
const avifTile * tile = &decoder->data->tiles.tile[i];
if ((frameIndex >= tile->input->samples.count) || !tile->input->samples.sample[frameIndex].sync) {
return AVIF_FALSE;
}
}
return AVIF_TRUE;
}
uint32_t avifDecoderNearestKeyframe(const avifDecoder * decoder, uint32_t frameIndex)
{
if (!decoder->data) {
// Nothing has been parsed yet
return 0;
}
for (; frameIndex != 0; --frameIndex) {
if (avifDecoderIsKeyframe(decoder, frameIndex)) {
break;
}
}
return frameIndex;
}
// Returns the number of available rows in decoder->image given a color or alpha subimage.
static uint32_t avifGetDecodedRowCount(const avifDecoder * decoder, const avifTileInfo * info, const avifImage * image)
{
if (info->decodedTileCount == info->tileCount) {
return image->height;
}
if (info->decodedTileCount == 0) {
return 0;
}
if (decoder->data->meta->sampleTransformExpression.count > 0) {
// TODO(yguyon): Support incremental Sample Transforms
return 0;
}
if ((info->grid.rows > 0) && (info->grid.columns > 0)) {
// Grid of AVIF tiles (not to be confused with AV1 tiles).
const uint32_t tileHeight = decoder->data->tiles.tile[info->firstTileIndex].height;
return AVIF_MIN((info->decodedTileCount / info->grid.columns) * tileHeight, image->height);
} else {
// Non-grid image.
return image->height;
}
}
uint32_t avifDecoderDecodedRowCount(const avifDecoder * decoder)
{
if (decoder->data->tileInfos[AVIF_ITEM_COLOR].tileCount == 0) {
// decoder->imageContentToDecode & AVIF_IMAGE_CONTENT_COLOR_AND_ALPHA
// was likely 0 when avifDecoderNextImage() was called.
// avifDecoderDecodedRowCount() only describes decoder->image->yuvPlanes[0].
// There is no available luma plane, so return 0 decoded rows.
return 0;
}
uint32_t minRowCount = decoder->image->height;
for (int c = 0; c < AVIF_ITEM_CATEGORY_COUNT; ++c) {
if (c == AVIF_ITEM_GAIN_MAP) {
const avifImage * const gainMap = decoder->image->gainMap ? decoder->image->gainMap->image : NULL;
if (gainMap != NULL && gainMap->height != 0 && decoder->data->tileInfos[AVIF_ITEM_GAIN_MAP].tileCount != 0) {
uint32_t gainMapRowCount = avifGetDecodedRowCount(decoder, &decoder->data->tileInfos[AVIF_ITEM_GAIN_MAP], gainMap);
if (gainMap->height != decoder->image->height) {
const uint32_t scaledGainMapRowCount =
(uint32_t)floorf((float)gainMapRowCount / gainMap->height * decoder->image->height);
// Make sure it matches the formula described in the comment of avifDecoderDecodedRowCount() in avif.h.
AVIF_CHECKERR((uint32_t)lround((double)scaledGainMapRowCount / decoder->image->height *
decoder->image->gainMap->image->height) <= gainMapRowCount,
0);
gainMapRowCount = scaledGainMapRowCount;
}
minRowCount = AVIF_MIN(minRowCount, gainMapRowCount);
}
continue;
}
const uint32_t rowCount = avifGetDecodedRowCount(decoder, &decoder->data->tileInfos[c], decoder->image);
minRowCount = AVIF_MIN(minRowCount, rowCount);
}
return minRowCount;
}
avifResult avifDecoderRead(avifDecoder * decoder, avifImage * image)
{
avifResult result = avifDecoderParse(decoder);
if (result != AVIF_RESULT_OK) {
return result;
}
result = avifDecoderNextImage(decoder);
if (result != AVIF_RESULT_OK) {
return result;
}
// If decoder->image->imageOwnsYUVPlanes is true and decoder->image is not used after this call,
// the ownership of the planes in decoder->image could be transferred here instead of copied.
// However most codec_*.c implementations allocate the output buffer themselves and return a
// view, unless some postprocessing is applied (container-level grid reconstruction for
// example), so the first condition rarely holds.
// The second condition does not hold either: it is not required by the documentation in avif.h.
return avifImageCopy(image, decoder->image, AVIF_PLANES_ALL);
}
avifResult avifDecoderReadMemory(avifDecoder * decoder, avifImage * image, const uint8_t * data, size_t size)
{
avifDiagnosticsClearError(&decoder->diag);
avifResult result = avifDecoderSetIOMemory(decoder, data, size);
if (result != AVIF_RESULT_OK) {
return result;
}
return avifDecoderRead(decoder, image);
}
avifResult avifDecoderReadFile(avifDecoder * decoder, avifImage * image, const char * filename)
{
avifDiagnosticsClearError(&decoder->diag);
avifResult result = avifDecoderSetIOFile(decoder, filename);
if (result != AVIF_RESULT_OK) {
return result;
}
return avifDecoderRead(decoder, image);
}
|