diff --git a/CMakeLists.txt b/CMakeLists.txt index fc2cba0..acf7bf1 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -1,7 +1,8 @@ cmake_minimum_required(VERSION 3.24) -project(ThumbGen VERSION 0.1.2 LANGUAGES CXX) +project(ThumbGen VERSION 0.1.3 LANGUAGES CXX) find_package(OpenImageIO 3.2 CONFIG REQUIRED) +find_package(OpenColorIO 2.5 CONFIG REQUIRED) find_package(Imath CONFIG REQUIRED) find_package(OpenEXR 3.5 CONFIG REQUIRED) find_package(nlohmann_json 3.11 CONFIG REQUIRED) @@ -9,6 +10,25 @@ list(APPEND CMAKE_MODULE_PATH "${CMAKE_CURRENT_SOURCE_DIR}/cmake") find_package(LittleCMS2 REQUIRED) find_package(JPEG REQUIRED) find_package(ZLIB REQUIRED) +find_package(TIFF 4.7 REQUIRED) +if(UNIX AND TARGET TIFF::tiff) + get_target_property(THUMBGEN_TIFF_TYPE TIFF::tiff TYPE) + if(THUMBGEN_TIFF_TYPE STREQUAL "STATIC_LIBRARY") + find_package(libdeflate CONFIG REQUIRED) + find_package(zstd CONFIG REQUIRED) + find_package(WebP CONFIG REQUIRED) + if(NOT TARGET Deflate::Deflate) + add_library(Deflate::Deflate ALIAS libdeflate::libdeflate_static) + endif() + if(NOT TARGET ZSTD::ZSTD) + add_library(ZSTD::ZSTD ALIAS zstd::libzstd_static) + endif() + if(NOT TARGET CMath::CMath) + add_library(CMath::CMath INTERFACE IMPORTED) + set_property(TARGET CMath::CMath PROPERTY INTERFACE_LINK_LIBRARIES m) + endif() + endif() +endif() include(cmake/Skcms.cmake) option(THUMBGEN_VERIFY_DEPENDENCY_VERSIONS "Require the versions used by the locked SDKs" OFF) file(READ "${CMAKE_CURRENT_SOURCE_DIR}/dependencies/versions.json" THUMBGEN_DEPENDENCY_LOCK) @@ -46,8 +66,10 @@ file(READ "${CMAKE_CURRENT_SOURCE_DIR}/schemas/errors-v1.json" THUMBGEN_ERROR_RE configure_file(src/error_registry.h.in generated/error_registry.h @ONLY) set_property(DIRECTORY APPEND PROPERTY CMAKE_CONFIGURE_DEPENDS "${CMAKE_CURRENT_SOURCE_DIR}/schemas/errors-v1.json") -add_library(thumbgen_core STATIC src/core.cpp src/colour_plan.cpp src/resize_srgb.cpp src/color_input.cpp src/cms_input.cpp src/cmyk_jpeg.cpp src/selection.cpp src/files.cpp src/quantize.cpp src/data_preview.cpp src/data_image.cpp src/selected_input.cpp src/cryptomatte.cpp src/sampled_id.cpp src/deep_flatten.cpp src/deep_reader.cpp src/deep_selection.cpp) +add_library(thumbgen_core STATIC src/core.cpp src/colour_plan.cpp src/resize_srgb.cpp src/color_input.cpp src/cms_input.cpp src/cmyk_jpeg.cpp src/jpeg_rows.cpp src/selection.cpp src/files.cpp src/quantize.cpp src/data_preview.cpp src/data_image.cpp src/selected_input.cpp src/cryptomatte.cpp src/sampled_id.cpp src/deep_flatten.cpp src/deep_reader.cpp src/deep_selection.cpp) option(THUMBGEN_PNG_SCANLINE "Use bounded native PNG16 decode for eligible integer colour sources" ON) +target_sources(thumbgen_core PRIVATE src/exr_rows.cpp src/png_rows.cpp src/tiff_rows.cpp + src/other_rows.cpp src/hdr_rows.cpp src/dpx_rows.cpp src/bmp_rows.cpp src/webp_rows.cpp src/tga_rows.cpp) if(THUMBGEN_PNG_SCANLINE) target_compile_definitions(thumbgen_core PRIVATE THUMBGEN_PNG_SCANLINE=1) endif() @@ -56,8 +78,9 @@ target_include_directories(thumbgen_core PUBLIC ${CMAKE_CURRENT_SOURCE_DIR}/incl target_include_directories(thumbgen_core PRIVATE ${CMAKE_CURRENT_BINARY_DIR}/generated) target_link_libraries(thumbgen_core PUBLIC nlohmann_json::nlohmann_json PRIVATE OpenImageIO::OpenImageIO Imath::Imath OpenEXR::OpenEXRCore) target_link_libraries(thumbgen_core PRIVATE LittleCMS2::LittleCMS2) +target_link_libraries(thumbgen_core PRIVATE OpenColorIO::OpenColorIO) target_link_libraries(thumbgen_core PRIVATE JPEG::JPEG) -target_link_libraries(thumbgen_core PRIVATE ZLIB::ZLIB thumbgen_skcms) +target_link_libraries(thumbgen_core PRIVATE ZLIB::ZLIB TIFF::TIFF thumbgen_skcms) if(WIN32) get_filename_component(THUMBGEN_JPEG_PREFIX "${JPEG_INCLUDE_DIR}" DIRECTORY) find_file(THUMBGEN_JPEG_RUNTIME NAMES jpeg8.dll libjpeg-8.dll jpeg62.dll PATHS "${THUMBGEN_JPEG_PREFIX}/bin" NO_DEFAULT_PATH REQUIRED) @@ -98,15 +121,15 @@ if(THUMBGEN_EXR_NOZERO) endif() target_link_libraries(thumbgen PRIVATE thumbgen_runtime) option(THUMBGEN_C2_PNG_STREAM "Opt-in exact incremental PNG with bounded buffer admission" OFF) +add_library(thumbgen_c2 STATIC src/c2_resize.cpp) +target_compile_features(thumbgen_c2 PRIVATE cxx_std_20) +if(MSVC) + target_compile_options(thumbgen_c2 PRIVATE /O2 /fp:precise /utf-8) +else() + target_compile_options(thumbgen_c2 PRIVATE -O2 -fno-fast-math -ffp-contract=off) +endif() +target_link_libraries(thumbgen_core PRIVATE thumbgen_c2) if(THUMBGEN_C2_PNG_STREAM) - add_library(thumbgen_c2 STATIC src/c2_resize.cpp) - target_compile_features(thumbgen_c2 PRIVATE cxx_std_20) - if(MSVC) - target_compile_options(thumbgen_c2 PRIVATE /O2 /fp:precise /utf-8) - else() - target_compile_options(thumbgen_c2 PRIVATE -O2 -fno-fast-math -ffp-contract=off) - endif() - target_link_libraries(thumbgen_core PRIVATE thumbgen_c2) target_compile_definitions(thumbgen_core PRIVATE THUMBGEN_C2_PNG_STREAM=1) target_compile_definitions(thumbgen_runtime PRIVATE THUMBGEN_C2_PNG_STREAM=1) endif() @@ -188,6 +211,18 @@ if(THUMBGEN_REQUIRE_FULL_TESTS) endif() endif() if(BUILD_TESTING) + add_executable(thumbgen_png_tiff_rows_tests tests/test_png_tiff_rows.cpp) + target_include_directories(thumbgen_png_tiff_rows_tests PRIVATE src) + target_link_libraries(thumbgen_png_tiff_rows_tests PRIVATE thumbgen_core OpenImageIO::OpenImageIO TIFF::TIFF ZLIB::ZLIB) + add_test(NAME core_png_tiff_rows COMMAND thumbgen_png_tiff_rows_tests) + add_executable(thumbgen_other_rows_tests tests/test_other_rows.cpp) + target_link_libraries(thumbgen_other_rows_tests PRIVATE thumbgen_core OpenImageIO::OpenImageIO) + add_test(NAME core_other_rows COMMAND thumbgen_other_rows_tests) + set_tests_properties(core_png_tiff_rows core_other_rows PROPERTIES TIMEOUT 120 LABELS "regression" + ENVIRONMENT_MODIFICATION + "PATH=path_list_prepend:$;LD_LIBRARY_PATH=path_list_prepend:$") + add_executable(thumbgen_bounded_exr_tests tests/test_bounded_exr.cpp) + target_link_libraries(thumbgen_bounded_exr_tests PRIVATE thumbgen_core OpenImageIO::OpenImageIO OpenEXR::OpenEXRCore) add_executable(thumbgen_exr_profile_tests tests/test_exr_profile.cpp) target_include_directories(thumbgen_exr_profile_tests PRIVATE src) target_link_libraries(thumbgen_exr_profile_tests PRIVATE thumbgen_core) @@ -236,6 +271,11 @@ if(BUILD_TESTING) add_test(NAME core_fast_colour COMMAND thumbgen_fast_colour_tests) set_tests_properties(core_fast_colour PROPERTIES ENVIRONMENT_MODIFICATION "PATH=path_list_prepend:$;LD_LIBRARY_PATH=path_list_prepend:$") + add_executable(thumbgen_jpeg_rows_tests tests/test_jpeg_rows.cpp) + target_link_libraries(thumbgen_jpeg_rows_tests PRIVATE thumbgen_core OpenImageIO::OpenImageIO LittleCMS2::LittleCMS2) + add_test(NAME core_jpeg_rows COMMAND thumbgen_jpeg_rows_tests) + set_tests_properties(core_jpeg_rows PROPERTIES TIMEOUT 120 ENVIRONMENT_MODIFICATION + "PATH=path_list_prepend:$;LD_LIBRARY_PATH=path_list_prepend:$") add_executable(thumbgen_resize_srgb_tests tests/test_resize_srgb.cpp) target_include_directories(thumbgen_resize_srgb_tests PRIVATE ${CMAKE_CURRENT_SOURCE_DIR}/src) target_link_libraries(thumbgen_resize_srgb_tests PRIVATE thumbgen_core OpenImageIO::OpenImageIO) @@ -476,6 +516,10 @@ if(BUILD_TESTING) message(FATAL_ERROR "The explicit test Python is unavailable; refusing to omit public tests") endif() if(Python3_Interpreter_FOUND) + add_test(NAME core_bounded_exr COMMAND ${Python3_EXECUTABLE} + ${CMAKE_CURRENT_SOURCE_DIR}/tests/run_exr_pipeline.py --exe $) + set_tests_properties(core_bounded_exr PROPERTIES TIMEOUT 120 LABELS "exr;regression" ENVIRONMENT_MODIFICATION + "PATH=path_list_prepend:$;LD_LIBRARY_PATH=path_list_prepend:$") add_executable(thumbgen_cms_tests tests/test_cms_input.cpp src/cms_input.cpp) target_include_directories(thumbgen_cms_tests PRIVATE src) target_compile_features(thumbgen_cms_tests PRIVATE cxx_std_17) @@ -498,6 +542,20 @@ if(BUILD_TESTING) message(FATAL_ERROR "Full tests require THUMBGEN_TEST_PROTOCOL=ON") endif() if(THUMBGEN_TEST_PROTOCOL) + add_test(NAME public_bounded_jpeg COMMAND ${Python3_EXECUTABLE} + ${CMAKE_CURRENT_SOURCE_DIR}/tests/test_bounded_jpeg_cli.py --exe $ + --fixture-exe $ + --schema-dir ${CMAKE_CURRENT_SOURCE_DIR}/schemas --runtime-dir $) + set_tests_properties(public_bounded_jpeg PROPERTIES TIMEOUT 240 LABELS "protocol;colour;scheduler") + add_test(NAME public_bounded_png_tiff COMMAND ${Python3_EXECUTABLE} + ${CMAKE_CURRENT_SOURCE_DIR}/tests/test_bounded_png_tiff_cli.py --exe $ + --reference-probe $ + --schema-dir ${CMAKE_CURRENT_SOURCE_DIR}/schemas --runtime-dir $) + add_test(NAME public_bounded_other COMMAND ${Python3_EXECUTABLE} + ${CMAKE_CURRENT_SOURCE_DIR}/tests/test_bounded_other_cli.py --exe $ + --schema-dir ${CMAKE_CURRENT_SOURCE_DIR}/schemas --runtime-dir $) + set_tests_properties(public_bounded_png_tiff public_bounded_other + PROPERTIES TIMEOUT 360 LABELS "protocol;colour;scheduler") add_test(NAME public_integer_colour COMMAND ${Python3_EXECUTABLE} ${CMAKE_CURRENT_SOURCE_DIR}/tests/test_integer_cli.py --exe $ --schema-dir ${CMAKE_CURRENT_SOURCE_DIR}/schemas --runtime-dir $) @@ -506,7 +564,7 @@ if(BUILD_TESTING) ${CMAKE_CURRENT_SOURCE_DIR}/tests/test_color_input.py --exe $ --probe-exe $ --schema-dir ${CMAKE_CURRENT_SOURCE_DIR}/schemas --runtime-dir $) - # Budget the whole 20-method suite, including independent probe launches; + # Budget the whole suite, including independent probe launches; # each child still has its separate 45-second limit in the Python test. set_tests_properties(public_color_input PROPERTIES TIMEOUT 180 LABELS "protocol;colour") add_test(NAME public_sampled_id COMMAND ${Python3_EXECUTABLE} @@ -555,7 +613,7 @@ endif() option(THUMBGEN_BUILD_COLOUR_PROBE "Build the product API colour acceptance probe" OFF) -if(THUMBGEN_BUILD_COLOUR_PROBE) +if(THUMBGEN_BUILD_COLOUR_PROBE OR (BUILD_TESTING AND Python3_Interpreter_FOUND AND THUMBGEN_TEST_PROTOCOL)) add_executable(thumbgen_colour_probe tests/tools/colour_probe.cpp) target_link_libraries(thumbgen_colour_probe PRIVATE thumbgen_core) endif() diff --git a/README.en.md b/README.en.md index 874e122..08a5e2f 100644 --- a/README.en.md +++ b/README.en.md @@ -8,7 +8,7 @@ ThumbGen makes thumbnails from standard images and complex EXRs, fast. Decode on Fast, EXR-aware previews for production pipelines. -`0.1.2` · [Apache-2.0](LICENSE) +`0.1.3` · [Apache-2.0](LICENSE) ## Where it fits @@ -66,7 +66,7 @@ These are actual ThumbGen outputs from publicly redistributable EXR samples. [Im Available for Windows x64 and Linux x64, including CentOS 7.9 and Rocky Linux 9 environments. -Read OpenEXR, PNG, JPEG, TIFF, WebP, TGA, BMP, Radiance HDR and DPX; write JPEG, PNG and lossy WebP. Special formats and image layouts have [some restrictions](docs/en/color-cms.md). Run `thumbgen capabilities --json` to see the formats available in your copy. +Read OpenEXR, PNG, JPEG, TIFF, WebP, TGA, BMP, Radiance HDR and DPX. Write JPEG, PNG and lossy WebP. See the [large-preview guide](docs/en/large-previews.md) for bounded layouts and budget settings. Run `thumbgen capabilities --json` to see the formats available in your copy. ## Quick start diff --git a/README.md b/README.md index f5802d3..5e90d69 100644 --- a/README.md +++ b/README.md @@ -8,7 +8,7 @@ ThumbGen 为普通图片和复杂 EXR 快速生成缩略图。一次解码输出 为制作管线提供快速、懂 EXR 的预览能力。 -`0.1.2` · [Apache-2.0](LICENSE) +`0.1.3` · [Apache-2.0](LICENSE) ## 适用场景 @@ -66,7 +66,7 @@ PNG、JPEG、TIFF 等常见图片也能处理;支持 Alpha、方向、多 part 支持 Windows x64 和 Linux x64,已在 CentOS 7.9、Rocky Linux 9 等环境使用。 -可读取 OpenEXR、PNG、JPEG、TIFF、WebP、TGA、BMP、Radiance HDR 和 DPX,输出 JPEG、PNG 和有损 WebP。特殊格式与图像布局有[部分限制](docs/color-cms.md),可用 `thumbgen capabilities --json` 查看当前程序的格式支持。 +可读取 OpenEXR、PNG、JPEG、TIFF、WebP、TGA、BMP、Radiance HDR 和 DPX,输出 JPEG、PNG 和有损 WebP。支持有界解码的布局与预算设置见[大图预览](docs/large-previews.md)。可用 `thumbgen capabilities --json` 查看当前程序的格式支持。 ## 快速开始 diff --git a/docs/README.md b/docs/README.md index cd992ad..bf5debb 100644 --- a/docs/README.md +++ b/docs/README.md @@ -7,6 +7,7 @@ | [快速上手](getting-started.md) | 第一次运行与常用操作 | | [安装](installation.md) | 程序目录与运行环境 | | [命令参考](cli.md) | 尺寸、格式、背景与资源设置 | +| [大图预览](large-previews.md) | 有界解码布局、内存预算与回退 | | [图层与序列](selection.md) | 选择主画面并保持连续帧一致 | | [色彩管理](color-cms.md) | OCIO、ICC 与透明度 | | [数据预览](data-preview.md) | 深度、法线、矢量与 ID | diff --git a/docs/cli.md b/docs/cli.md index 75b35f9..01f4522 100644 --- a/docs/cli.md +++ b/docs/cli.md @@ -42,7 +42,9 @@ thumbgen convert frame.exr --output preview.jpg --ocio-config config.ocio --inpu 数据预览使用 `--visualize`、`--channels`、`--data-range MIN,MAX` 和 `--invalid-values black|magenta|error`,详见[数据预览](data-preview.md)。Deep 颜色使用 `--deep-mode flatten`,详见[Deep EXR](public-deep.md)。 -使用 `--visualize auto` 在一次转换中按现有规则选颜色图。没有颜色候选时,程序可以预览一个可确定的 Cryptomatte 家族。跨 part 的编号层会一起读取。多个家族或不完整的布局会给出错误。指定 part、通道或 Deep 展平时,自动模式遵循显式选择。色彩管理选项只用于颜色预览。 +使用 `--visualize auto` 在一次转换中选择颜色或 Cryptomatte 预览。默认策略优先选择明确命名的主画面,其次优先选择各 part 内的顶层 RGB。若未指定 part 或通道,且多个 EXR part 仍有颜色候选,自动模式可在其余候选都是阴影、环境光遮蔽或 Fresnel 等可识别的辅助通道组时,选用唯一一组无前缀的 RGB 或 RGBA。 + +没有颜色候选时,自动模式可以跨 part 预览单个 Cryptomatte 家族。默认选择策略下,多个家族中唯一的 `crypto_object` 或 `CryptoObject` 优先(不区分大小写)。无法消除歧义或所选布局无效时会报错。指定 part、通道或 Deep 展平时,自动模式遵循显式选择。色彩管理选项只用于颜色预览。 ## 执行预算与时限 diff --git a/docs/color-cms.md b/docs/color-cms.md index d52a9a4..6042347 100644 --- a/docs/color-cms.md +++ b/docs/color-cms.md @@ -16,7 +16,9 @@ thumbgen convert frame.exr --output preview.jpg --ocio-config config.ocio --inpu ## 嵌入 ICC -受支持的单张 PNG、JPEG、TIFF、WebP 会自动应用 RGB / 灰度 ICC。显式指定输入空间会覆盖嵌入配置,因此只应在确认源颜色含义时使用。 +受支持的单张 PNG、JPEG、TIFF、WebP 会自动应用 RGB 或灰度 ICC。自动选择输入空间且未指定配置、显示器或视图时,这类文件使用 `ocio://default`,不受 `OCIO` 环境变量影响。显式选择配置或显示器与视图时,遵循上文的项目配置规则。显式指定输入空间会覆盖嵌入配置。 + +用于 ICC 转换的项目配置须能解析标准非线性场景参考空间 `srgb_rec709_scene`。可直接用标准名声明该色彩空间,也可声明对应别名并设置同名 interop ID。CMYK ICC 仍遵循显式指定或从环境继承的项目配置。 带可靠 ICC 的四通道 CMYK TIFF,以及受支持的 8-bit baseline Adobe CMYK/YCCK JPEG,可以转为 RGB 预览。没有可靠 profile、分色布局不支持或 ICC 损坏时会报告错误;给 CMYK 强行指定 RGB 空间不能替代正确转换。 diff --git a/docs/en/README.md b/docs/en/README.md index e1caafb..f0f4a91 100644 --- a/docs/en/README.md +++ b/docs/en/README.md @@ -7,6 +7,7 @@ | [Getting started](getting-started.md) | First conversion and common tasks | | [Installation](installation.md) | Program folder and runtime setup | | [Command reference](cli.md) | Sizes, formats, backgrounds and resources | +| [Large previews](large-previews.md) | Bounded layouts, admission and fallback | | [Layers and sequences](selection.md) | Pick layers and keep frames consistent | | [Color management](color-cms.md) | OCIO, ICC and transparency | | [Data previews](data-preview.md) | Depth, normals, vectors and IDs | diff --git a/docs/en/cli.md b/docs/en/cli.md index 3a8d272..faf40e7 100644 --- a/docs/en/cli.md +++ b/docs/en/cli.md @@ -42,7 +42,9 @@ thumbgen convert frame.exr --output preview.jpg --ocio-config config.ocio --inpu Data previews use `--visualize`, `--channels`, `--data-range MIN,MAX` and `--invalid-values black|magenta|error`. See [data previews](data-preview.md). For Deep color, use `--deep-mode flatten`; see [Deep EXR](public-deep.md). -Use `--visualize auto` to apply the standard color selection rules in one conversion. When there are no color candidates, it can preview an unambiguous Cryptomatte family, reading its numbered layers across parts. Multiple families or an incomplete layout produce an error. Part, channel and Deep flattening options take precedence. Color management options apply only to color previews. +Use `--visualize auto` to select a color or Cryptomatte preview in one conversion. The default selection policy prefers recognized primary images, then top-level RGB within each part. If multiple EXR parts still compete and no explicit part or channels were requested, auto mode can select a unique unprefixed RGB or RGBA group when all the other remaining color candidates are recognized auxiliary passes such as shadow, ambient occlusion, or Fresnel. + +When there are no color candidates, automatic mode can preview a single Cryptomatte family across parts. Under the default selection policy, a unique `crypto_object` or `CryptoObject` family (case-insensitive) takes priority among multiple families. Ambiguous selections and invalid selected layouts produce errors. Part, channel and Deep flattening options take precedence. Color management options apply only to color previews. ## Resource budgets and timeouts diff --git a/docs/en/color-cms.md b/docs/en/color-cms.md index 4b54ac6..19bf227 100644 --- a/docs/en/color-cms.md +++ b/docs/en/color-cms.md @@ -16,7 +16,9 @@ Input space comes from `--input-space` first, otherwise file metadata. With no s ## Embedded ICC -Supported single-image PNG, JPEG, TIFF and WebP inputs automatically use RGB / grayscale ICC profiles. An explicit input space overrides the embedded profile, so use it only when you know the source colors. +Supported single-image PNG, JPEG, TIFF and WebP inputs automatically use RGB or grayscale ICC profiles. With automatic input space and no explicit config, display or view, these files use `ocio://default` regardless of `OCIO`. An explicit config or display/view request follows the project configuration rules above. An explicit input space overrides the embedded profile. + +A project config used for ICC must resolve the standard nonlinear scene-referred `srgb_rec709_scene` bridge. Use the canonical color-space name or a declared alias with that interop ID. CMYK ICC continues to use the project's configuration when one is supplied or inherited. Four-channel CMYK TIFF and supported 8-bit baseline Adobe CMYK/YCCK JPEG inputs with reliable ICC profiles can produce RGB previews. Missing profiles, unsupported ink layouts or damaged ICC data cause errors. Assigning an RGB space to CMYK is not a substitute for proper conversion. diff --git a/docs/en/installation.md b/docs/en/installation.md index 0f4ac64..dfe5676 100644 --- a/docs/en/installation.md +++ b/docs/en/installation.md @@ -4,7 +4,7 @@ Use the complete ThumbGen folder for your platform. Keep the supplied DLLs on Windows; preserve the bin/lib layout and executable permissions on Linux. Do not copy only the executable. -Download the matching `thumbgen-0.1.2-*.zip` or `.tar.gz` and check the accompanying `SHA256SUMS`. Both archives contain one fixed `ThumbGen/` directory, with `bin/`, `share/`, `licenses/` and, on Linux, `lib/` immediately underneath. The directory name has no version or platform suffix; no renaming or moving is needed. +Download the matching `thumbgen-0.1.3-*.zip` or `.tar.gz` and check the accompanying `SHA256SUMS`. Both archives contain one fixed `ThumbGen/` directory, with `bin/`, `share/`, `licenses/` and, on Linux, `lib/` immediately underneath. The directory name has no version or platform suffix; no renaming or moving is needed. On Windows, extract into `%LOCALAPPDATA%/Programs/` to get `%LOCALAPPDATA%/Programs/ThumbGen/bin/thumbgen.exe`. In PowerShell: @@ -16,7 +16,7 @@ On Linux, extract into `$HOME/.local/opt/` to get `$HOME/.local/opt/ThumbGen/bin ```sh mkdir -p "$HOME/.local/opt" -tar -xzf thumbgen-0.1.2-linux-x86_64-glibc217.tar.gz -C "$HOME/.local/opt" +tar -xzf thumbgen-0.1.3-linux-x86_64-glibc217.tar.gz -C "$HOME/.local/opt" "$HOME/.local/opt/ThumbGen/bin/thumbgen" --version --json ``` diff --git a/docs/en/large-previews.md b/docs/en/large-previews.md new file mode 100644 index 0000000..c26a6ad --- /dev/null +++ b/docs/en/large-previews.md @@ -0,0 +1,27 @@ +# Large image previews + +[Documentation](README.md) · [简体中文](../large-previews.md) + +```sh +thumbgen convert renders/frame.exr --output-dir previews --size 960x960 --size 425x260 --preset balanced --max-decode-mib 512 --thread-budget 1 --memory-budget-mib 1024 +``` + +The balanced preset can decode eligible sources once for up to two preview sizes, keeping the resize buffers and a bounded portion of the native source in memory. This route normally starts at 8 million source pixels. Flat EXR with a shifted or cropped display window can use it at smaller sizes. Preview sizes are aspect-ratio-preserving bounds and never enlarge the source. + +| Input | Layouts eligible for bounded colour previews | +| --- | --- | +| JPEG | 8-bit grayscale, RGB and YCbCr. Multiscan and progressive images also reserve their complete coefficient tables. Adobe CMYK/YCCK uses the profile-aware full-image route. | +| PNG | 8- or 16-bit grayscale or RGB, with optional alpha and matching native channels. This includes transparency expanded to alpha. Adam7 retains a complete native frame and needs a larger budget. | +| TIFF | Interleaved unsigned 8- or 16-bit grayscale or RGB, with optional alpha, stored in strips or tiles using no compression, Deflate, LZW or PackBits. White-is-zero grayscale is eligible without alpha. The selected page pays for compressed scratch and the decoded strip or tile row. | +| Flat OpenEXR | Scanline or single-level tiled files with uniformly HALF or FLOAT selected RGB/RGBA channels, unit sampling, and NONE, RLE, ZIPS, ZIP or PIZ compression. Supports part selection and data and display windows, including negative origins. | +| Radiance HDR | RGBE rows decoded to float. | +| DPX | Uncompressed, single-element unsigned RGB at 8, 10, 12 or 16 bits with supported packing and row alignment. | +| BMP | Uncompressed 24-bit RGB and 32-bit RGB(A). | +| TGA | Uncompressed, non-interleaved 24-bit RGB and 32-bit RGBA. The decoder retains a native frame. | +| WebP | Still lossy RGB/RGBA. The decoder retains compressed input and a native frame. Lossless and animated inputs use the checked full-image path where the layout fits its decoder limits. | + +The bounded layouts use extents of at most 65,536 pixels per axis, with smaller limits where the format requires them. EXR bounds include an 8 MiB metadata allocation limit, a 1,048,576-entry offset table and a 64 MiB unpacked chunk limit. Preview workspace is also capped. Unsupported layouts, other presets, additional output sizes, and data/Deep previews use the applicable existing path when its limits allow. If the file fails validation or its plan exceeds a limit, the affected job reports an error before writing a preview. + +`--max-decode-mib` (default 512) limits the per-job decode plan. For bounded previews this includes native rows or retained frames, codec scratch, colour and resize buffers, preview output buffers, and ICC reservation where applicable. `--memory-budget-mib` sets the isolated controller's shared admission budget. It covers a fixed reserve for the controller and idle workers plus each admitted job's estimated incremental usage and margin. They are application limits and estimates. `decode_limit_exceeded` means the decode plan did not fit, and `task_memory_exceeds_budget` means the controller could not admit the task. In JSON output, `execution.admission_mib` shows the estimated incremental memory per admitted job. + +See [color management](color-cms.md) for OCIO and ICC behavior and [the CLI reference](cli.md) for batch budget options. diff --git a/docs/en/selection.md b/docs/en/selection.md index d8841ed..36c04d3 100644 --- a/docs/en/selection.md +++ b/docs/en/selection.md @@ -20,6 +20,8 @@ thumbgen convert multipart.exr --output preview.jpg --part-name beauty `--part N` selects a zero-based index and cannot be combined with `--part-name`. Use [data previews](data-preview.md) for depth, normals and IDs. +With `--visualize auto` and the default selection policy, a unique unprefixed RGB(A) group can resolve ambiguity between parts when all remaining candidates are recognized auxiliary AOVs such as shadows or ambient occlusion. Without a color candidate, the same mode can preview a Cryptomatte family across parts. A unique object family named `crypto_object` or `CryptoObject` takes precedence over other families, regardless of case. Other ambiguities require an explicit part, channel group or Cryptomatte family. + ## Keep sequences consistent Give related batch jobs the same `sequence_id` to keep their selected layers and channels consistent. A later frame with missing or changed channels reports an error instead of silently selecting another image. diff --git a/docs/installation.md b/docs/installation.md index 5ecc9c7..010a106 100644 --- a/docs/installation.md +++ b/docs/installation.md @@ -4,7 +4,7 @@ 使用适合平台的完整 ThumbGen 程序目录。Windows 需要保留随附 DLL;Linux 需要保留 bin/lib 相对位置和执行权限。不要只复制单个可执行文件。 -下载匹配平台的 `thumbgen-0.1.2-*.zip` 或 `.tar.gz`,先核对随附的 `SHA256SUMS`。两个压缩包都只有固定的 `ThumbGen/` 外层目录,里面直接是 `bin/`、`share/`、`licenses/`,Linux 另有 `lib/`;目录名不含版本或平台,无需解压后改名或移动。 +下载匹配平台的 `thumbgen-0.1.3-*.zip` 或 `.tar.gz`,先核对随附的 `SHA256SUMS`。两个压缩包都只有固定的 `ThumbGen/` 外层目录,里面直接是 `bin/`、`share/`、`licenses/`,Linux 另有 `lib/`;目录名不含版本或平台,无需解压后改名或移动。 Windows 解压到 `%LOCALAPPDATA%/Programs/`,得到 `%LOCALAPPDATA%/Programs/ThumbGen/bin/thumbgen.exe`。PowerShell 可运行: @@ -16,7 +16,7 @@ Linux 解压到 `$HOME/.local/opt/`,得到 `$HOME/.local/opt/ThumbGen/bin/thum ```sh mkdir -p "$HOME/.local/opt" -tar -xzf thumbgen-0.1.2-linux-x86_64-glibc217.tar.gz -C "$HOME/.local/opt" +tar -xzf thumbgen-0.1.3-linux-x86_64-glibc217.tar.gz -C "$HOME/.local/opt" "$HOME/.local/opt/ThumbGen/bin/thumbgen" --version --json ``` diff --git a/docs/large-previews.md b/docs/large-previews.md new file mode 100644 index 0000000..523a670 --- /dev/null +++ b/docs/large-previews.md @@ -0,0 +1,27 @@ +# 大图预览 + +[文档目录](README.md) · [English](en/large-previews.md) + +```sh +thumbgen convert renders/frame.exr --output-dir previews --size 960x960 --size 425x260 --preset balanced --max-decode-mib 512 --thread-budget 1 --memory-budget-mib 1024 +``` + +使用 `balanced` 时,符合条件的输入可一次解码并生成最多两种尺寸,只保留有限的原生解码数据和缩放缓冲区。通常从 800 万源像素开始启用。具有位移或裁切显示窗口的平面 EXR 在较小尺寸也可使用。输出按给定尺寸等比缩小,最多保留原尺寸。 + +| 输入格式 | 支持有界颜色预览的布局 | +| --- | --- | +| JPEG | 8 位灰度、RGB 和 YCbCr。多扫描和渐进式图像还需为完整系数表预留内存。Adobe CMYK/YCCK 使用支持 ICC 的整图路径。 | +| PNG | 原生通道匹配的 8 位、16 位灰度和 RGB,可带 Alpha,也支持将透明度展开为 Alpha。Adam7 需保留完整原生帧。 | +| TIFF | 无压缩、Deflate、LZW 或 PackBits 的 8 位、16 位无符号交错灰度和 RGB,可带 Alpha,支持条带和瓦片。白色为零的灰度布局仅在无 Alpha 时适用。所选页需为压缩数据及解码后的条带或一行瓦片预留内存。 | +| 平面 OpenEXR | 扫描线或单层瓦片,所选 RGB/RGBA 通道均为 HALF 或均为 FLOAT,通道采样率为 1。支持 NONE、RLE、ZIPS、ZIP、PIZ 压缩、part 选择及带负坐标的数据窗口和显示窗口。 | +| Radiance HDR | RGBE 行解码为浮点。 | +| DPX | 无压缩的单元素无符号 RGB,支持符合打包与行对齐要求的 8、10、12、16 位布局。 | +| BMP | 无压缩的 24 位 RGB 和 32 位 RGB(A)。 | +| TGA | 无压缩、非交错的 24 位 RGB 和 32 位 RGBA。解码器保留完整原生帧。 | +| WebP | 有损静态 RGB/RGBA。解码器保留压缩输入和原生帧。无损和动画可在满足解码限制时使用整图路径。 | + +有界布局每边最多 65,536 像素,格式本身可能有更低的限制。EXR 的限制包括 8 MiB 元数据分配、最多 1,048,576 个偏移表条目和 64 MiB 解包块。缩放工作缓冲区也有上限。其他布局、预设、更多输出尺寸以及数据或 Deep 预览,在满足对应限制时沿用现有处理路径。输入校验失败或超出计划限制时,该任务会在写出预览前报告错误。 + +`--max-decode-mib` 默认为 512,限制每个任务的解码计划。有界预览的计划包含原生数据、解码器临时区、色彩与缩放缓冲区、输出缓冲区以及所需的 ICC 预留。独立进程的共享 `--memory-budget-mib` 覆盖控制器与空闲进程的固定预留,以及活跃任务的增量估算与余量。这些是应用级限制和估算。`decode_limit_exceeded` 表示解码计划超限,`task_memory_exceeds_budget` 表示控制器无法准入该任务。JSON 输出中的 `execution.admission_mib` 是任务获准后的增量内存估算。 + +OCIO 和 ICC 的行为见[色彩管理](color-cms.md),批处理预算选项见[命令参考](cli.md)。 diff --git a/docs/selection.md b/docs/selection.md index 288d99d..709f5c7 100644 --- a/docs/selection.md +++ b/docs/selection.md @@ -20,6 +20,8 @@ thumbgen convert multipart.exr --output preview.jpg --part-name beauty `--part N` 也可按从 0 开始的索引选择,但不能与 `--part-name` 同时使用。深度、法线、ID 等数据通道请使用[数据预览](data-preview.md)。 +`--visualize auto` 使用默认选择策略时,如果其他 part 的候选都是阴影或环境光遮蔽等已识别的辅助 AOV,可选用唯一一组无前缀 RGB(A)。没有颜色候选时,此模式可跨 part 预览 Cryptomatte 家族。多个家族中唯一的 `crypto_object` 或 `CryptoObject` 优先,名称不区分大小写。其他歧义需显式指定 part、通道组或 Cryptomatte 家族。 + ## 连续帧保持一致 在批处理任务中使用相同的 `sequence_id`,即可固定同一组图层与通道。后续帧缺失或改变通道时报告错误,而不会悄悄选择另一张图。 diff --git a/scripts/ci/run.py b/scripts/ci/run.py index 8dfea31..d0227f6 100644 --- a/scripts/ci/run.py +++ b/scripts/ci/run.py @@ -63,7 +63,7 @@ def audit_release(directory): raise RuntimeError('Release codemodel has no configurations') expected = {'thumbgen': 'EXECUTABLE', 'thumbgen_core': 'STATIC_LIBRARY', 'thumbgen_runtime': 'STATIC_LIBRARY', 'thumbgen_schedule': 'STATIC_LIBRARY', - 'thumbgen_skcms': 'STATIC_LIBRARY'} + 'thumbgen_skcms': 'STATIC_LIBRARY', 'thumbgen_c2': 'STATIC_LIBRARY'} for config in model['configurations']: targets = [json.loads((reply / item['jsonFile']).read_text()) for item in config['targets']] actual = {target['name']: target['type'] for target in targets if target['type'] != 'UTILITY'} diff --git a/scripts/linux/test-deps-lock.json b/scripts/linux/test-deps-lock.json index 1565e40..099b4e7 100644 --- a/scripts/linux/test-deps-lock.json +++ b/scripts/linux/test-deps-lock.json @@ -2,6 +2,13 @@ "python": "cp311", "platform": "manylinux2014_x86_64", "wheels": [ + { + "name": "Pillow", + "version": "11.3.0", + "filename": "pillow-11.3.0-cp311-cp311-manylinux2014_x86_64.manylinux_2_17_x86_64.whl", + "sha256": "91da1d88226663594e3f6b4b8c3c8d85bd504117d043740a8e0ec449087cc494", + "url": "https://files.pythonhosted.org/packages/13/92/dcdd147ab02daf405387f0218dcf792dc6dd5b14d2573d40b4caeef01059/pillow-11.3.0-cp311-cp311-manylinux2014_x86_64.manylinux_2_17_x86_64.whl" + }, { "name": "jsonschema", "version": "4.26.0", diff --git a/src/bmp_rows.cpp b/src/bmp_rows.cpp new file mode 100644 index 0000000..242f89f --- /dev/null +++ b/src/bmp_rows.cpp @@ -0,0 +1,34 @@ +#include "other_rows_internal.h" + +namespace thumbgen::detail::other_rows { +OtherRowsProbe bmp(Source& source) { + std::array header{}; + source.read(0,header.data(),18,"truncated BMP header"); + const auto dib=le32(header.data()+14); + const bool core=dib==12; + require(core || dib==40 || dib==52 || dib==56 || dib==108 || dib==124, + "unsupported BMP header length"); + source.read(18,header.data()+18,core?8:36,"truncated BMP layout"); + const auto width=core?le16(header.data()+18):le32(header.data()+18); + const auto encoded_height=core?le16(header.data()+20):le32(header.data()+22); + const auto height=!core && encoded_height>0x7fffffffU?0U-encoded_height:encoded_height; + require(width<=0x7fffffffU && height<=0x7fffffffU,"invalid BMP dimensions"); + const auto pixels=dimensions(width,height,65536,"BMP dimensions exceed supported limits"); + const auto planes=le16(header.data()+(core?22:26)),bits=le16(header.data()+(core?24:28)); + require(planes==1 && (bits==1 || bits==4 || bits==8 || bits==16 || bits==24 || bits==32), + "invalid BMP planes or bit depth"); + const auto compression=core?0:le32(header.data()+30); + const auto offset=le32(header.data()+10); + require(offset>=14+dib && offset<=source.size,"invalid BMP pixel offset"); + const auto stride=(std::uint64_t(width)*bits+31)/32*4; + const auto codec=plugin_bytes+2*stride; + if(compression || (bits!=24 && bits!=32)) { + const auto retained=compression==1 || compression==2?pixels:0; + return fallback(source,"bmp",pixels,codec+retained,retained); + } + source.extent(offset,stride*height,"truncated BMP image data"); + reserve(codec,source.budget,"BMP header and decode rows exceed decode budget"); + auto spec=metadata(source,"bmp"); + return supported(source,"bmp",std::move(spec),0,codec); +} +} diff --git a/src/bounded_read.h b/src/bounded_read.h new file mode 100644 index 0000000..6625028 --- /dev/null +++ b/src/bounded_read.h @@ -0,0 +1,77 @@ +#pragma once +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +namespace thumbgen::detail { +// Planning is metadata-only. The factory runs once, after admission. The +// reader writes tightly packed native rows in increasing, contiguous order, +// with no sample conversion. The selected ImageSpec describes the data window, +// channel order, sample type, and alpha association. A one-part metadata probe +// can publish this spec before the decoder is opened. +// A tile/strip/frame reader owns its cache and declares that storage here. +class NativeRowSource { +public: + virtual ~NativeRowSource()=default; + virtual void read(int first,int last,void* destination)=0; + virtual void finish()=0; +}; +struct NativeReadPlan { + unsigned pixel_bytes=0; + std::uint64_t retained_bytes=0; + std::uint64_t codec_bytes=0; + std::function()> open; +}; +struct BoundedReadMemory { + std::uint64_t source=0,working=0,output=0,codec=0; +}; +inline constexpr std::uint64_t bounded_mib=1024*1024; +inline constexpr std::size_t bounded_sampler_limit=128*bounded_mib; +inline constexpr std::size_t native_colour_block_pixels=1024*1024; +inline std::pair fit_preview(int width,int height,int limit_width,int limit_height) { + const double scale=std::min({double(limit_width)/width,double(limit_height)/height,1.0}); + return {std::max(1,int(std::lround(width*scale))),std::max(1,int(std::lround(height*scale)))}; +} +inline std::uint64_t checked_bytes_add(std::uint64_t a,std::uint64_t b) { + if(b>std::numeric_limits::max()-a)throw std::overflow_error("buffer size addition overflow"); + return a+b; +} +inline std::uint64_t checked_bytes_mul(std::uint64_t a,std::uint64_t b) { + if(a && b>std::numeric_limits::max()/a)throw std::overflow_error("buffer size multiplication overflow"); + return a*b; +} +inline std::uint64_t bounded_total(const BoundedReadMemory& m) { + return checked_bytes_add(checked_bytes_add(m.source,m.working),checked_bytes_add(m.output,m.codec)); +} +// Both preview buffers may be live during the first output's finish. The +// existing output envelope covers colour, orient, composite and encode copies. +inline BoundedReadMemory bounded_read_memory(std::uint64_t width,std::uint64_t height,unsigned channels, + unsigned native_pixel_bytes,std::uint64_t retained,std::uint64_t codec,std::uint64_t cms, + std::uint64_t sampler,const std::vector>& sizes) { + if(!width || !height || width>65536 || height>65536 || (channels!=3 && channels!=4) || + !native_pixel_bytes || native_pixel_bytes>32 || !sampler || sizes.empty() || sizes.size()>2) + throw std::invalid_argument("invalid bounded read layout"); + const auto block=std::min(width*height,native_colour_block_pixels); + BoundedReadMemory m; + m.source=checked_bytes_add(checked_bytes_add(retained,cms),(block+width)*native_pixel_bytes); + m.working=checked_bytes_add(sampler,block*channels*sizeof(float)); + std::uint64_t largest=0; + for(auto [w,h]:sizes) { + if(w<=0 || h<=0 || std::uint64_t(w)>width || std::uint64_t(h)>height) + throw std::invalid_argument("invalid bounded preview size"); + const auto pixels=std::uint64_t(w)*std::uint64_t(h); + largest=std::max(largest,pixels); + m.output+=pixels*channels*sizeof(float); + } + m.output+=largest*5*4*sizeof(float); + m.codec=checked_bytes_add(codec,largest*8+bounded_mib); + return m; +} +} // namespace thumbgen::detail diff --git a/src/budget.cpp b/src/budget.cpp index 450a120..c02030d 100644 --- a/src/budget.cpp +++ b/src/budget.cpp @@ -17,17 +17,7 @@ Bytes multiply(Bytes a,Bytes b) { if(a && b>std::numeric_limits::max()/a)throw std::overflow_error("memory estimate multiplication overflow"); return a*b; } -} -MemoryEstimate estimate_memory(const ImageFootprint& s) { - if(!s.data_width || !s.data_height || !s.display_width || !s.display_height || !s.channel_span || - (s.selected_channels!=3 && s.selected_channels!=4) || !s.output_width || !s.output_height || - !s.threads || s.threads>256 || !s.source_sample_bytes || s.source_sample_bytes>8 || - (s.native_categorical && s.selected_channels!=4) || s.source_pixel_bytes>32 || - (s.source_pixel_bytes && s.source_pixel_bytescanvas)throw std::invalid_argument("preview footprint exceeds display canvas"); +MemoryEstimate buffered_memory(const ImageFootprint& s,Bytes data,Bytes canvas,Bytes preview) { MemoryEstimate e; e.source=multiply(data,s.source_pixel_bytes?s.source_pixel_bytes:multiply(s.channel_span,s.source_sample_bytes)); if(s.source_buffer_bytes) { @@ -86,6 +76,28 @@ MemoryEstimate estimate_memory(const ImageFootprint& s) { const auto bounded=c2_memory(s.data_width,s.data_height,s.selected_channels,s.output_width,s.output_height,s.cms_buffer_bytes); e.source=bounded.source;e.working=bounded.working;e.output=bounded.output;e.codec=bounded.codec; } + e.codec=add(e.codec,s.source_codec_bytes); + return e; +} +} +MemoryEstimate estimate_memory(const ImageFootprint& s) { + if(!s.data_width || !s.data_height || !s.display_width || !s.display_height || !s.channel_span || + (s.selected_channels!=3 && s.selected_channels!=4) || !s.output_width || !s.output_height || + !s.threads || s.threads>256 || !s.source_sample_bytes || s.source_sample_bytes>8 || + (s.native_categorical && s.selected_channels!=4) || s.source_pixel_bytes>32 || + (s.source_pixel_bytes && s.source_pixel_bytescanvas)throw std::invalid_argument("preview footprint exceeds display canvas"); + MemoryEstimate e; + if(s.bounded.source) { + if(s.c2_stream || s.native_categorical || s.deep_buffer_bytes || s.source_buffer_bytes) + throw std::invalid_argument("invalid bounded source footprint"); + e.source=s.bounded.source;e.working=s.bounded.working;e.output=s.bounded.output;e.codec=s.bounded.codec; + } else { + e=buffered_memory(s,data,canvas,preview); + } // Provisional measured-headroom model, to calibrate across codecs and platforms. e.worker=add(128*mib,multiply(s.threads,8*mib)); Bytes dynamic=add(add(e.source,e.working),add(e.output,e.codec)); diff --git a/src/budget.h b/src/budget.h index c24b7fa..6f6d5f0 100644 --- a/src/budget.h +++ b/src/budget.h @@ -1,4 +1,5 @@ #pragma once +#include "bounded_read.h" #include #include #include @@ -21,6 +22,8 @@ struct ImageFootprint { bool integer_linear=false; // Native integer source plus full linear float image and orientation. bool srgb8=false; // Native UINT8 source and bounded linear-preview resize workspace. bool c2_stream=false; // Opt-in bounded integer PNG plan; never a full-source fallback. + std::uint64_t source_codec_bytes=0; // Decoder allocations before or alongside source reads. + BoundedReadMemory bounded; // Populated by the controller for a bounded native read. }; struct MemoryEstimate { // incremental is charged per active task; worker is already reserved by the pool. diff --git a/src/c2_png_rows.h b/src/c2_png_rows.h index 635c948..1c93240 100644 --- a/src/c2_png_rows.h +++ b/src/c2_png_rows.h @@ -1,5 +1,6 @@ #pragma once #include "colour_plan.h" +#include "bounded_read.h" #include #include #include @@ -10,16 +11,16 @@ namespace thumbgen::detail { // Reader owns OIIO and translates read errors; this adapter never retries. class C2PngRows { int width_,height_,channels_,decoded_=0; - const ColourPlan& plan_; + unsigned pixel_bytes_; std::function read_; std::function transform_; std::size_t total_,base_=0,count_=0,next_=0,row_used_=0,row_pixels_=0; std::vector native_,row_; std::vector linear_; void block(){ - base_=next_;count_=std::min(total_-next_,std::size_t(1048576)); + base_=next_;count_=std::min(total_-next_,native_colour_block_pixels); if(!count_)throw std::runtime_error("C2 source exhausted"); - const auto pixel_bytes=channels_*plan_.sample_bytes; + const auto pixel_bytes=pixel_bytes_; std::size_t used=0; while(used read, - std::function transform):width_(w),height_(h),channels_(c),plan_(plan),read_(std::move(read)),transform_(std::move(transform)),total_(std::size_t(w)*h), - native_(std::min(total_,std::size_t(1048576))*c*plan.sample_bytes),row_(std::size_t(w)*c*plan.sample_bytes),linear_(std::min(total_,std::size_t(1048576))*c){} + std::function transform): + C2PngRows(w,h,c,c*plan.sample_bytes,std::move(read),std::move(transform)){} + C2PngRows(int w,int h,int c,unsigned pixel_bytes,std::function read, + std::function transform):width_(w),height_(h),channels_(c),pixel_bytes_(pixel_bytes), + read_(std::move(read)),transform_(std::move(transform)),total_(std::size_t(w)*h), + native_(std::min(total_,native_colour_block_pixels)*pixel_bytes),row_(std::size_t(w)*pixel_bytes),linear_(std::min(total_,native_colour_block_pixels)*c){} void get(int y,float* output){ std::size_t pixel=std::size_t(y)*width_,remaining=width_; while(remaining){ diff --git a/src/c2_resize.cpp b/src/c2_resize.cpp index 9145d05..44fd210 100644 --- a/src/c2_resize.cpp +++ b/src/c2_resize.cpp @@ -68,6 +68,10 @@ struct Slice { }; } namespace thumbgen::detail { +void c2_srgb8_to_linear(const void* input,float* output,std::size_t samples){ + const auto* bytes=static_cast(input); + for(std::size_t i=0;i>& outputs,size_t& total){ + static bool plan(int w,int h,int c,const std::vector>& outputs,size_t& total,size_t limit){ total=0; if(w<=0 || h<=0 || w>65536 || h>65536 || (c!=3 && c!=4) || outputs.empty() || outputs.size()>2)return false; - auto account=[&](size_t n){if(n>c2_workspace_limit-total)return false;total+=n;return true;}; + auto account=[&](size_t n){if(n>limit-total)return false;total+=n;return true;}; if(!account(sizeof(Impl)+size_t(w)*c*sizeof(float)+4*size_t(w)*sizeof(void*)+4096))return false; for(auto [dw,dh]:outputs){ if(dw<=0 || dh<=0 || dw>w || dh>h)return false; @@ -102,63 +106,84 @@ struct C2Resize::Impl { if(!account(sizeof(Owner)) || !account(query.total))return false; const size_t state=sizeof(Slice)+sizeof(Task)+frame_limit; const size_t slab=query.mutable_end-query.mutable_begin+15; - if(size_t(query.columns)>(c2_workspace_limit-total)/state || !account(size_t(query.columns)*state))return false; - if(size_t(query.columns-1)>(c2_workspace_limit-total)/slab || !account(size_t(query.columns-1)*slab))return false; + if(size_t(query.columns)>(limit-total)/state || !account(size_t(query.columns)*state))return false; + if(size_t(query.columns-1)>(limit-total)/slab || !account(size_t(query.columns-1)*slab))return false; } return true; } - Impl(int w,int h,int c,const std::vector>& outputs):width(w),height(h),channels(c){ + Impl(int w,int h,int c,const std::vector>& outputs,size_t limit, + std::vector* output_errors):width(w),height(h),channels(c){ require(w>0 && h>0 && (c==3 || c==4) && !outputs.empty() && outputs.size()<=2); - size_t planned=0;if(!plan(w,h,c,outputs,planned))throw C2PlanLimit(); + require(!output_errors || output_errors->size()==outputs.size()); + size_t planned=0;if(!plan(w,h,c,outputs,planned,limit))throw C2PlanLimit(); allocation.owner=this; auto account=[&](size_t n){if(n>planned-bytes)throw C2ContractError("C2 allocation exceeds admitted workspace");bytes+=n;}; // Pointer-vector capacity and allocator overhead are reserved up front; // pinned geometry has at most one slice per input column, two outputs. account(sizeof(Impl)+size_t(w)*c*sizeof(float)+4*size_t(w)*sizeof(void*)+4096); row.resize(size_t(w)*c); + owners.resize(outputs.size()); for(size_t k=0;k0 && dh>0 && dw<=w && dh<=h); - account(sizeof(Owner));auto owner=std::make_unique();auto& r=owner->resize; - setup(r,w,h,c,dw,dh,row.data(),&allocation); - allocation.available=planned-bytes; - if(!stbir_build_samplers(&r)){if(allocation.limited)throw C2PlanLimit();throw std::bad_alloc();} - require(r.splits==1 && r.samplers->num_column_slices<=w); - auto* info=r.samplers; - // Input callbacks supply the row; zero stride avoids forming a - // fictitious full-image pointer from the one-row allocation. - info->input_stride_bytes=0; - account(info->alloced_total); - const auto initial=*info->split_info; - auto* begin=static_cast(initial.decode_buffer_alloc); - auto* end=reinterpret_cast(info->horizontal.contributors); - require(end>begin); - for(int b=0;bnum_column_slices;++b){ - account(sizeof(Slice)+sizeof(Task)+frame_limit+(b?size_t(end-begin)+15:0)); - auto slice=std::make_unique();slice->info=info;slice->column=b;slice->output=k;slice->state=initial; - if(b){ - slice->workspace.resize(size_t(end-begin)+15); - auto* base=reinterpret_cast((reinterpret_cast(slice->workspace.data())+15)&~uintptr_t(15)); - auto rebase=[&](void* p)->void*{auto* q=static_cast(p);require(q>=begin && qstate.decode_buffer_alloc=rebase(initial.decode_buffer_alloc); - slice->state.ring_buffer_alloc=rebase(initial.ring_buffer_alloc); - slice->state.vertical_buffer_alloc=rebase(initial.vertical_buffer_alloc); + if(output_errors && (*output_errors)[k])continue; + const auto used=bytes,slice_count=slices.size(); + try { +#ifdef THUMBGEN_OUTPUT_FAULT_TESTS + output_fault_index(k); +#endif + auto [dw,dh]=outputs[k];require(dw>0 && dh>0 && dw<=w && dh<=h); + account(sizeof(Owner));auto owner=std::make_unique();auto& r=owner->resize; + setup(r,w,h,c,dw,dh,row.data(),&allocation); + allocation.available=planned-bytes; + if(!stbir_build_samplers(&r)){if(allocation.limited)throw C2PlanLimit();throw std::bad_alloc();} + require(r.splits==1 && r.samplers->num_column_slices<=w); + auto* info=r.samplers; + // Callbacks supply a single row without advancing an input pointer. + info->input_stride_bytes=0; + account(info->alloced_total); + const auto initial=*info->split_info; + auto* begin=static_cast(initial.decode_buffer_alloc); + auto* end=reinterpret_cast(info->horizontal.contributors); + require(end>begin); + for(int b=0;bnum_column_slices;++b){ + account(sizeof(Slice)+sizeof(Task)+frame_limit+(b?size_t(end-begin)+15:0)); + auto slice=std::make_unique();slice->info=info;slice->column=b;slice->output=k;slice->state=initial; + if(b){ + slice->workspace.resize(size_t(end-begin)+15); + auto* base=reinterpret_cast((reinterpret_cast(slice->workspace.data())+15)&~uintptr_t(15)); + auto rebase=[&](void* p)->void*{auto* q=static_cast(p);require(q>=begin && qstate.decode_buffer_alloc=rebase(initial.decode_buffer_alloc); + slice->state.ring_buffer_alloc=rebase(initial.ring_buffer_alloc); + slice->state.vertical_buffer_alloc=rebase(initial.vertical_buffer_alloc); + } + stbir__4K_alias_skew_buffers(info,&slice->state); + slices.push_back(std::move(slice)); } - stbir__4K_alias_skew_buffers(info,&slice->state); - slices.push_back(std::move(slice)); + owners[k]=std::move(owner); + } catch(const std::bad_alloc&) { + if(!output_errors)throw; + slices.resize(slice_count); + bytes=used; + (*output_errors)[k]=std::current_exception(); } - owners.push_back(std::move(owner)); } require(owners.capacity()*sizeof(owners[0])+slices.capacity()*sizeof(slices[0])<=4*size_t(w)*sizeof(void*)+4096); - require(bytes==planned); + require(bytes==planned || std::any_of(owners.begin(),owners.end(),[](const auto& owner){return !owner;})); } }; -bool C2Resize::workspace_plan(int w,int h,int c,const std::vector>& outputs,size_t& bytes){return Impl::plan(w,h,c,outputs,bytes);} -C2Resize::C2Resize(int w,int h,int c,const std::vector>& outputs):impl_(std::make_unique(w,h,c,outputs)){} +bool C2Resize::workspace_plan(int w,int h,int c,const std::vector>& outputs,size_t& bytes,size_t limit){ + return Impl::plan(w,h,c,outputs,bytes,limit); +} +C2Resize::C2Resize(int w,int h,int c,const std::vector>& outputs,size_t limit, + std::vector* output_errors): + impl_(std::make_unique(w,h,c,outputs,limit,output_errors)){} C2Resize::~C2Resize()=default; size_t C2Resize::workspace_bytes()const{return impl_->bytes;} std::vector C2Resize::execute(const std::function& read,const std::vector& outputs){ auto& p=*impl_;require(!p.used && outputs.size()==p.owners.size());p.used=true; - for(size_t k=0;kresize.samplers->output_data=outputs[k];} + for(size_t k=0;kresize.samplers->output_data=outputs[k]; + } std::vector times(outputs.size(),0); for(auto& s:p.slices){ auto* part=s->info->column_slices+s->column; diff --git a/src/c2_resize.h b/src/c2_resize.h index 35b7d1f..d5c25e2 100644 --- a/src/c2_resize.h +++ b/src/c2_resize.h @@ -1,21 +1,28 @@ #pragma once +#include "c2_memory.h" #include +#include #include #include #include #include #include namespace thumbgen::detail { +void c2_srgb8_to_linear(const void* input,float* output,std::size_t samples); struct C2PlanLimit:std::runtime_error {C2PlanLimit():std::runtime_error("C2 workspace limit"){} }; struct C2ContractError:std::runtime_error {using std::runtime_error::runtime_error;}; -// Internal opt-in adapter. Construction fixes all geometry and allocates the +// Internal row sampler. Construction fixes all geometry and allocates the // original sampler tables plus bounded concurrent slice state, before decode. class C2Resize { public: // Geometry-only counting pass: no pixel access or dynamic allocations. // False means structural fallback; call before admission, construct after it. - static bool workspace_plan(int width,int height,int channels,const std::vector>& outputs,std::size_t& bytes); - C2Resize(int width,int height,int channels,const std::vector>& outputs); + static bool workspace_plan(int width,int height,int channels,const std::vector>& outputs, + std::size_t& bytes,std::size_t limit=c2_workspace_limit); + // Supplied errors disable their outputs and receive per-output allocation + // failures. A shared workspace or source failure still aborts the job. + C2Resize(int width,int height,int channels,const std::vector>& outputs, + std::size_t limit=c2_workspace_limit,std::vector* output_errors=nullptr); ~C2Resize(); C2Resize(const C2Resize&)=delete; C2Resize& operator=(const C2Resize&)=delete; diff --git a/src/colour_plan.cpp b/src/colour_plan.cpp index 4d1a90c..07c253e 100644 --- a/src/colour_plan.cpp +++ b/src/colour_plan.cpp @@ -8,6 +8,7 @@ namespace thumbgen::detail { ColourPlan colour_plan(const OIIO::ImageSpec& s,const std::string& format, bool eligible,bool layout,bool embedded,bool use_icc,const std::string& input) { ColourPlan p; + p.bounded_options=eligible; auto fallback=[&](const char* reason){p.route=ColourPlan::Route::reference;p.sample_bytes=4;p.fallback=reason;return p;}; if(!eligible)return fallback("Reference processing required by options or colour configuration"); if(!layout || !s.channelformats.empty() || (s.format!=OIIO::TypeDesc::UINT8 && s.format!=OIIO::TypeDesc::UINT16) || diff --git a/src/colour_plan.h b/src/colour_plan.h index 25eb277..c92f9f8 100644 --- a/src/colour_plan.h +++ b/src/colour_plan.h @@ -10,6 +10,9 @@ namespace thumbgen::detail { struct ColourPlan { enum class Route {reference,srgb8,integer_linear}; Route route=Route::reference; + // Options and effective configuration may permit bounded reference + // processing even when the fast native transform cannot represent a profile. + bool bounded_options=false; unsigned sample_bytes=4; // Stable ownership across returned/copyable plans; skcms curves point here. // Included in the pre-existing four-profile CMS metadata reservation. diff --git a/src/core.cpp b/src/core.cpp index 4a395cb..a27135d 100644 --- a/src/core.cpp +++ b/src/core.cpp @@ -5,9 +5,14 @@ #include "cms_input.h" #include "colour_plan.h" #include "png_scanline.h" -#ifdef THUMBGEN_C2_PNG_STREAM #include "c2_resize.h" #include "c2_png_rows.h" +#include "jpeg_rows.h" +#include "exr_rows.h" +#include "png_rows.h" +#include "tiff_rows.h" +#include "other_rows.h" +#ifdef THUMBGEN_C2_PNG_STREAM #include "c2_memory.h" #include "c2_png_metadata.h" #endif @@ -24,6 +29,7 @@ #include "sampled_id.h" #include "deep_selection.h" #include "deep_flatten.h" +#include #include #include #include @@ -38,6 +44,7 @@ #include #include #include +#include #include #include #include @@ -54,6 +61,24 @@ namespace fs = std::filesystem; namespace iba = OIIO::ImageBufAlgo; using Clock = std::chrono::steady_clock; using Failure=detail::FileFailure; +template +static void gray_rows_to_rgb(const void* source,float* out,std::size_t count,int components) { + const auto* bytes=static_cast(source); + const auto read=[&](std::size_t index) { + Sample value; + std::memcpy(&value,bytes+index*sizeof(Sample),sizeof(Sample)); + return float(value)*(1.0f/std::numeric_limits::max()); + }; + // Native blocks carry one luminance sample and, optionally, one alpha. + // Expand only into the float block used for colour processing and resize. + const bool alpha=components==4; + for(std::size_t i=0;igetColorSpace(standard); + declared=space && name==space->getName() && !space->isData() && + space->getReferenceSpaceType()==OCIO::REFERENCE_SPACE_SCENE && + (name==standard || std::string_view(space->getInteropID())==standard); + } catch(const OCIO::Exception& error) { + throw Failure("colour_config_failed",error.what()); + } + } + if(!declared || name.empty() || config.get_color_interop_id(name)!=standard || config.isColorSpaceLinear(name)) + throw Failure("colour_input_unsupported","ICC requires a declared standard srgb_rec709_scene OCIO bridge"); + return name; +} + struct Engine::Impl { Engine::Observer observer; Engine::Control control; bool converting=false; struct Pin {Json key,request;bool named;}; std::map sequences; - std::map> configs; - OIIO::ColorConfig* config(const std::string& name) { + struct Config { + OIIO::ColorConfig colour; + std::string icc_bridge; + explicit Config(const std::string& name):colour(name) {} + }; + std::map> configs; + Config& config(const std::string& name) { auto found=configs.find(name); - if(found!=configs.end())return found->second.get(); - auto value=std::make_unique(name); + if(found!=configs.end())return *found->second; + auto value=std::make_unique(name); // Do not cache failed configs: geterror() clears the error, and a later // job must not accidentally reuse OIIO's fallback as a valid config. - if(value->has_error())throw Failure("colour_config_failed",value->geterror()); - auto* result=value.get();configs.emplace(name,std::move(value));return result; + if(value->colour.has_error())throw Failure("colour_config_failed",value->colour.geterror()); + auto* result=value.get();configs.emplace(name,std::move(value));return *result; } }; Engine::Engine(Observer observer) : impl_(std::make_unique()) {impl_->observer=std::move(observer);} @@ -273,7 +326,33 @@ Json Engine::capabilities() { Json Engine::inspect(const std::string& input) { Json result{{"schema_version",1},{"type","inspection"},{"input",input},{"ok",false}}; - auto in=OIIO::ImageInput::open(input); + std::optional other; + try { + constexpr auto unlimited=std::numeric_limits::max(); + const auto jpeg=detail::probe_jpeg(input,unlimited); + std::error_code ec; + const auto bytes=jpeg?0:fs::file_size(fs::u8path(input),ec); + if(!jpeg && !ec) + other=detail::probe_other_rows(input,bytes,unlimited,OIIO::ImageSpec{},std::numeric_limits::max()); + const auto* spec=jpeg?&jpeg->spec:other && other->spec?&*other->spec:nullptr; + if(spec) { + auto part=spec_json(*spec,0); + part["candidates"]=candidates_json(*spec,0); + result["parts"]=Json::array({std::move(part)});result["ok"]=true; + return result; + } + } catch(const Failure& error) { + result["error"]={{"code","open_failed"},{"message",error.what()}}; + return result; + } + auto in=other?OIIO::ImageInput::create(other->format):OIIO::ImageInput::open(input); + if(other && in) { + OIIO::ImageSpec ignored; + if(!in->open(input,ignored)) { + result["error"]={{"code","open_failed"},{"message",in->geterror()}}; + return result; + } + } if(!in){result["error"]={{"code","open_failed"},{"message",OIIO::geterror()}};return result;} result["parts"]=Json::array(); OIIO::ImageSpec spec; @@ -339,14 +418,47 @@ Json Engine::convert(const Job& job) { // Ask unassociated formats to return straight RGB. In particular WebP // and PNG otherwise associate their nonlinear RGB in different spaces. read_config.attribute("oiio:UnassociatedAlpha",1); + const auto decode_budget=detail::checked_bytes_mul(job.options.max_decode_mib,detail::bounded_mib); bool container_icc=false; - try {container_icc=!data && detail::container_has_icc(job.input,job.options.input_space=="auto"?detail::icc_profile_limit:std::numeric_limits::max());} + std::optional jpeg; + std::optional other; + std::string probed_format; + try { + // OIIO opens progressive JPEGs by starting the decompressor. + // Keep that allocation out of metadata preparation. + const auto limit=!data && job.options.input_space=="auto"?detail::icc_profile_limit:std::numeric_limits::max(); + jpeg=detail::probe_jpeg(job.input,decode_budget,limit); + if(jpeg)probed_format="jpeg"; + else { + if(detail::preflight_png_header(source_path,decode_budget))probed_format="png"; + else if(detail::preflight_tiff_header(source_path,decode_budget))probed_format="tiff"; + else if(detail::preflight_exr_header(job.input))probed_format="openexr"; + else if((other=detail::probe_other_rows(job.input,stamp.size,decode_budget,read_config,limit))) + probed_format=other->format; + } + container_icc=!data && (jpeg?jpeg->has_icc:detail::container_has_icc(job.input,limit)); + } catch(const detail::CmsFailure& error){throw Failure("colour_input_unsupported",error.what());} - auto in=OIIO::ImageInput::open(job.input,&read_config); - if(!in){auto error=OIIO::geterror();verify_source();throw Failure("open_failed",error);} - const bool can_auto_crypto=detail::auto_cryptomatte_allowed(job.options) && std::string(in->format_name())=="openexr"; + OIIO::ImageInput::unique_ptr in; + auto open_input=[&] { + if(probed_format.empty())in=OIIO::ImageInput::open(job.input,&read_config); + else { + in=OIIO::ImageInput::create(probed_format); + if(in) { + OIIO::ImageSpec ignored; + if(in->open(job.input,ignored,read_config))return; + auto error=in->geterror();verify_source();throw Failure("open_failed",error); + } + } + if(!in){auto error=OIIO::geterror();verify_source();throw Failure("open_failed",error);} + }; + const bool deferred_other=other && other->spec.has_value(); + if(!jpeg && !deferred_other)open_input(); + const std::string input_format=jpeg?"jpeg":deferred_other?other->format:in->format_name(); + const bool can_auto_crypto=detail::auto_cryptomatte_allowed(job.options) && input_format=="openexr"; + const bool use_auto_exr_preferences=can_auto_crypto && job.options.selection_policy=="primary"; #if defined(THUMBGEN_EXR_PROFILE) && THUMBGEN_EXR_PROFILE - profile.enable(std::string(in->format_name())=="openexr"); + profile.enable(input_format=="openexr"); #endif if(!data && detail::container_separated_colour(job.input)) throw Failure("colour_input_unsupported","CMYK/separated input requires an external profile-aware conversion to RGB"); @@ -380,13 +492,16 @@ Json Engine::convert(const Job& job) { } for(int p=0;;++p) { OIIO::ImageSpec scanned; - if(can_auto_crypto?std::size_t(p)>=crypto_parts.size():!in->seek_subimage(p,0,scanned))break; + if(jpeg || deferred_other) { + if(p!=0)break; + scanned=jpeg?jpeg->spec:*other->spec; + } else if(can_auto_crypto?std::size_t(p)>=crypto_parts.size():!in->seek_subimage(p,0,scanned))break; const auto& candidate=can_auto_crypto?crypto_parts[p]:scanned; if(!data && job.options.input_space=="auto" && p>0 && (container_icc || candidate.find_attribute("ICCProfile"))) throw Failure("colour_input_unsupported","automatic ICC supports a single flat image, not multipart/multiframe input"); const bool supported_cmyk=job.options.input_space=="auto" && candidate.find_attribute("ICCProfile") && - ((std::string(in->format_name())=="tiff" && candidate.get_string_attribute("tiff:ColorSpace")=="CMYK") || - (std::string(in->format_name())=="jpeg" && !candidate.get_string_attribute("jpeg:ColorSpace").empty())); + ((input_format=="tiff" && candidate.get_string_attribute("tiff:ColorSpace")=="CMYK") || + (input_format=="jpeg" && !candidate.get_string_attribute("jpeg:ColorSpace").empty())); if(!data && detail::separated_colour(candidate) && !supported_cmyk) throw Failure("colour_input_unsupported","CMYK/separated input requires an external profile-aware conversion to RGB; input_space cannot undo decoder conversion"); ++part_count; @@ -428,17 +543,26 @@ Json Engine::convert(const Job& job) { } for(const auto& group:eligible)choices.push_back({p,candidate,group}); } + bool preferred_object=false; if(can_auto_crypto && choices.empty() && !has_deep && !crypto_families.empty()) { - if(crypto_families.size()!=1) - throw Failure("ambiguous_channels","multiple Cryptomatte families; specify visualization and channels"); - crypto_family=crypto_families.front();crypto=true;data=true; + auto family=crypto_families.begin(); + if(crypto_families.size()>1) { + const auto end=crypto_families.end(); + if(use_auto_exr_preferences)family=std::find_if(family,end,detail::is_object_crypto_family); + if(!use_auto_exr_preferences || family==end || std::any_of(family+1,end,detail::is_object_crypto_family)) + throw Failure("ambiguous_channels","multiple Cryptomatte families; specify visualization and channels"); + preferred_object=true; + } + crypto_family=*family;crypto=true;data=true; } if(automatic)mapping.mode=crypto?detail::DataMode::cryptomatte:detail::DataMode::colour; if(crypto && part_exists) { crypto_layout=detail::crypto_layout(std::move(crypto_parts),crypto_family,crypto_part); const auto& first=crypto_layout->layers.front(); const auto& first_spec=crypto_layout->parts.at(first.part); - detail::Candidate group{crypto_family,"data",automatic?"automatic Cryptomatte coverage overview":"explicit Cryptomatte coverage overview",first.channels}; + const auto reason=preferred_object?"automatic Cryptomatte coverage overview for the object family": + automatic?"automatic Cryptomatte coverage overview":"explicit Cryptomatte coverage overview"; + detail::Candidate group{crypto_family,"data",reason,first.channels}; all_choices.push_back({first.part,first_spec,group}); choices.push_back({first.part,first_spec,std::move(group)}); } @@ -446,6 +570,16 @@ Json Engine::convert(const Job& job) { if(job.options.channels.empty() && job.options.selection_policy=="primary" && std::any_of(choices.begin(),choices.end(),[](const auto& c){return detail::is_primary(c.spec,c.candidate);})) choices.erase(std::remove_if(choices.begin(),choices.end(),[](const auto& c){return !detail::is_primary(c.spec,c.candidate);}),choices.end()); + else if(use_auto_exr_preferences && choices.size()>1) { + auto auxiliary=[](const auto& choice){return detail::is_auxiliary_aov(choice.spec,choice.candidate);}; + const auto root=std::find_if_not(choices.begin(),choices.end(),auxiliary); + if(root!=choices.end() && detail::is_root_rgb(root->spec,root->candidate) && std::all_of(root+1,choices.end(),auxiliary)) { + auto chosen=std::move(*root); + chosen.candidate.reason="unique unprefixed RGB group among auxiliary AOVs"; + choices.clear(); + choices.push_back(std::move(chosen)); + } + } Json request=detail::selection_request(job); auto pin=impl_->sequences.find(job.sequence_id); auto describe=[&](const Choice& choice) { @@ -515,22 +649,22 @@ Json Engine::convert(const Job& job) { } if(all_skip) { verify_source(); - in->close(); + if(in)in->close(); for(const auto& output:job.outputs)r["outputs"].push_back({{"path",output.path},{"status","skipped"},{"reason","output_exists"},{"existing_policy","skip"}}); r["status"]="skipped";r["ok"]=true;r["timings_ms"]["total"]=ms(started);return r; } auto input_plan=detail::channel_plan(spec,channels,data); const bool cmyk=!data && detail::separated_colour(spec); - const bool cmyk_jpeg=cmyk && std::string(in->format_name())=="jpeg"; + const bool cmyk_jpeg=cmyk && input_format=="jpeg"; OIIO::ImageSpec raw_cmyk; if(cmyk) { raw_cmyk=spec;raw_cmyk.nchannels=4;raw_cmyk.channelnames={"C","M","Y","K"};raw_cmyk.alpha_channel=-1; raw_cmyk.erase_attribute("ICCProfile"); input_plan=detail::channel_plan(raw_cmyk,{0,1,2,3},false); } - const std::string input_format=in->format_name(); const bool icc_format=input_format=="png" || input_format=="jpeg" || input_format=="tiff" || input_format=="webp"; - const bool use_icc=!data && !deep && icc_format && job.options.input_space=="auto" && (container_icc || spec.find_attribute("ICCProfile")); + const bool embedded_icc=container_icc || spec.find_attribute("ICCProfile"); + const bool use_icc=!data && !deep && icc_format && job.options.input_space=="auto" && embedded_icc; if(crypto)input_plan.pixel_bytes=detail::crypto_source_pixel_bytes(*crypto_layout); std::optional sampled; if(mapping.mode==detail::DataMode::id) { @@ -541,15 +675,23 @@ Json Engine::convert(const Job& job) { double scale=std::min({double(out.width)/dw,double(out.height)/dh,1.0}); sizes.emplace_back(std::max(1,int(std::lround(dw*scale))),std::max(1,int(std::lround(dh*scale)))); } - sampled=detail::sampled_id_plan(spec,in->format_name(),channels,mapping,sizes); + sampled=detail::sampled_id_plan(spec,input_format,channels,mapping,sizes); if(sampled)r["source_read"]={{"mode","sampled_blocks"},{"grid",{sampled->x.size(),sampled->y.size()}}, {"block",{sampled->block_width,sampled->block_height}},{"calls",sampled->x_blocks.size()*sampled->y_blocks.size()},{"buffer_bytes",sampled->peak_bytes}}; } // Decide native storage from metadata before decode admission. The // pinned built-in colour contract is checked after admission, before IO. - std::string requested_config=job.options.ocio_config; - if(requested_config.empty()){const char* env=std::getenv("OCIO");requested_config=env?env:"";} - if(requested_config.empty())requested_config="ocio://default"; + std::string config_name=job.options.ocio_config; + const char* config_basis="explicit"; + if(config_name.empty()) { + const bool standalone_icc=use_icc && !cmyk && part_count==1 && spec.depth==1 && + job.options.display.empty() && job.options.view.empty(); + if(!standalone_icc) { + if(const char* environment=std::getenv("OCIO"))config_name=environment; + } + config_basis=config_name.empty()?"builtin":"environment"; + if(config_name.empty())config_name="ocio://default"; + } std::string requested_input=job.options.input_space; if(requested_input=="auto") { requested_input=spec.get_string_attribute("oiio:ColorSpace"); @@ -558,12 +700,12 @@ Json Engine::convert(const Job& job) { const bool plain_rgb=spec.nchannels==3 && spec.alpha_channel==-1 && spec.channelnames==std::vector({"R","G","B"}) && channels==std::vector({0,1,2}); const bool plain_rgba=spec.nchannels==4 && spec.alpha_channel==3 && - spec.get_int_attribute("oiio:UnassociatedAlpha",0)==1 && spec.channelnames==std::vector({"R","G","B","A"}) && channels==std::vector({0,1,2,3}); + const bool straight_alpha=spec.get_int_attribute("oiio:UnassociatedAlpha",0)!=0; const auto colour_plan=detail::colour_plan(spec,input_format, !impl_->control.reference_colour && !data && !deep && !cmyk && - job.options.preset=="balanced" && requested_config=="ocio://default" && job.options.display.empty(), - plain_rgb || plain_rgba,container_icc || spec.find_attribute("ICCProfile"),use_icc,requested_input); + job.options.preset=="balanced" && config_name=="ocio://default" && job.options.display.empty(), + plain_rgb || (plain_rgba && straight_alpha),embedded_icc,use_icc,requested_input); const bool fast_srgb=colour_plan.route==detail::ColourPlan::Route::srgb8; const bool integer_linear=colour_plan.route==detail::ColourPlan::Route::integer_linear; #ifdef THUMBGEN_PNG_SCANLINE @@ -576,21 +718,33 @@ Json Engine::convert(const Job& job) { const bool scanline_png=false; #endif bool c2_active=false; -#ifdef THUMBGEN_C2_PNG_STREAM - std::unique_ptr c2_resize; std::size_t c2_workspace_bytes=0; std::vector> c2_sizes; std::vector c2_previews; std::vector c2_resize_ms; + std::vector c2_output_errors; std::exception_ptr c2_preview_error; + const detail::NativeReadPlan* bounded_source=nullptr; + const auto cms_bytes=use_icc?detail::cms_reservation:0; + const auto orientation=spec.get_int_attribute("Orientation",1); + const bool transpose=orientation>=5 && orientation<=8; + const bool shifted_window=spec.x || spec.y || spec.full_x || spec.full_y || + spec.width!=spec.full_width || spec.height!=spec.full_height; + const bool large=std::uint64_t(spec.width)*spec.height>=8000000; + const auto png=input_format=="png"?detail::plan_png_rows(source_path,*in,spec,decode_budget):detail::PngRowPlan{}; + const auto tiff=input_format=="tiff"?detail::plan_tiff_rows(source_path,spec,part,decode_budget):detail::TiffRowPlan{}; + std::optional exr; + const bool native_gray=chosen.candidate.kind=="grey" && + ((spec.nchannels==1 && spec.alpha_channel==-1 && channels==std::vector({0,0,0})) || + (spec.nchannels==2 && spec.alpha_channel==1 && channels==std::vector({0,0,0,1}))); + auto source_codec_bytes=jpeg?jpeg->codec_bytes:other?other->fallback_codec_bytes: + png.fallback_codec_bytes+tiff.fallback_codec_bytes; +#ifdef THUMBGEN_C2_PNG_STREAM // A second output must allocate only after the first finishes/commits. // Its streaming consumer would need retired source rows: fall back // structurally before admission instead of buffering or redecoding. // A single output may defer resize errors until its original policy check. // Execution and admission share the same bounded buffer envelope. - const auto c2_decode_budget=job.options.max_decode_mib*1024ULL*1024ULL; - const auto c2_cms_reserve=use_icc?detail::cms_reservation:0; - std::uint64_t c2_dynamic_bytes=0; const bool c2_png=scanline_png || (integer_linear && spec.format==OIIO::TypeDesc::UINT8 && std::uint64_t(spec.width)*spec.height>=detail::png_scanline_min_pixels && detail::png_scanline_eligible(source_path,spec,input_format,colour_plan,true)); if(c2_png && spec.width<=65536 && spec.height<=65536 && job.outputs.size()==1 && @@ -605,18 +759,63 @@ Json Engine::convert(const Job& job) { if(std::uint64_t(w)*h>std::uint64_t(c2_largest_w)*c2_largest_h){c2_largest_w=w;c2_largest_h=h;} } if(c2_small_outputs){ - c2_dynamic_bytes=detail::c2_memory(spec.width,spec.height,spec.nchannels,c2_largest_w,c2_largest_h,c2_cms_reserve).dynamic(); - if(c2_dynamic_bytes<=c2_decode_budget){ + const auto memory=detail::c2_memory(spec.width,spec.height,spec.nchannels,c2_largest_w,c2_largest_h,cms_bytes); + if(detail::checked_bytes_add(memory.dynamic(),source_codec_bytes)<=decode_budget){ c2_active=detail::C2Resize::workspace_plan(spec.width,spec.height,spec.nchannels,c2_sizes,c2_workspace_bytes); } } } #endif + if(!c2_active && !data && !deep && !impl_->control.reference_colour && job.options.preset=="balanced" && + orientation>=1 && orientation<=8 && !job.outputs.empty() && job.outputs.size()<=2 && + spec.full_width<=65536 && spec.full_height<=65536) { + const detail::NativeReadPlan* candidate=nullptr; + if(input_format=="openexr" && (large || shifted_window)) { + exr=detail::probe_exr_rows(job.input,spec,part,channels); + if(exr)candidate=&exr->read; + } else if(!shifted_window && large) { + const bool rgb=plain_rgb || plain_rgba; + if(jpeg && (rgb || native_gray) && colour_plan.bounded_options)candidate=&jpeg->read; + else if(png.read.open && (rgb || native_gray))candidate=&png.read; + else if(tiff.read.open && (rgb || native_gray))candidate=&tiff.read; + else if(deferred_other && rgb)candidate=&other->read; + } + c2_sizes.clear(); + if(candidate && candidate->open) { + for(const auto& output:job.outputs) + c2_sizes.push_back(detail::fit_preview(spec.full_width,spec.full_height, + transpose?output.height:output.width,transpose?output.width:output.height)); + const auto components=unsigned(channels.size()); + if(detail::C2Resize::workspace_plan(spec.full_width,spec.full_height,components, + c2_sizes,c2_workspace_bytes,detail::bounded_sampler_limit) && + detail::bounded_total(detail::bounded_read_memory(spec.full_width,spec.full_height,components, + candidate->pixel_bytes,candidate->retained_bytes,candidate->codec_bytes,cms_bytes, + c2_workspace_bytes,c2_sizes))<=decode_budget) { + bounded_source=candidate; + source_codec_bytes=candidate->codec_bytes; + } + } + if(!bounded_source){exr.reset();c2_sizes.clear();} + } + const bool streaming=c2_active || bounded_source; + const bool bounded_gray=bounded_source && native_gray; + // Noninterlaced PNG still checks its row scratch and decoded raster + // individually. The scheduler charges both, including for small images. + if(!streaming && source_codec_bytes && (input_format!="png" || png.retains_frame)) { + // The complete-image plugin retains late APP entries during + // multiscan decode. Reserve a node for every possible segment. + if(jpeg && jpeg->multiscan)source_codec_bytes=detail::checked_bytes_add(source_codec_bytes,detail::checked_bytes_mul(stamp.size,32)); + const auto pixel_bytes=integer_linear?channels.size()*(colour_plan.sample_bytes+2*sizeof(float)): + fast_srgb?channels.size():input_plan.pixel_bytes; + const auto full_source=sampled?sampled->peak_bytes: + detail::checked_bytes_mul(std::uint64_t(spec.width)*spec.height,pixel_bytes); + if(detail::checked_bytes_add(detail::checked_bytes_add(full_source,source_codec_bytes),cms_bytes)>decode_budget) + throw Failure("decode_limit_exceeded","source and decoder scratch exceed decode budget"); + } if(impl_->control.planned) { auto span=std::minmax_element(channels.begin(),channels.end()); int display_width=spec.full_width,display_height=spec.full_height; - auto orientation=spec.get_int_attribute("Orientation",1); - if(orientation>=5 && orientation<=8)std::swap(display_width,display_height); + if(transpose)std::swap(display_width,display_height); int largest_w=1,largest_h=1;std::uint64_t largest_pixels=0; for(const auto& out:job.outputs) { double scale=std::min({double(out.width)/display_width,double(out.height)/display_height,1.0}); @@ -629,11 +828,15 @@ Json Engine::convert(const Job& job) { {"footprint",{{"data_width",spec.width},{"data_height",spec.height}, {"display_width",display_width},{"display_height",display_height}, {"channel_span",cmyk?4:*span.second-*span.first+1},{"selected_channels",data || deep?4:channels.size()}, - {"source_sample_bytes",colour_plan.linear()?colour_plan.sample_bytes:input_plan.sample_bytes},{"source_pixel_bytes",colour_plan.linear()?channels.size()*colour_plan.sample_bytes:input_plan.pixel_bytes}, + {"source_sample_bytes",bounded_gray?spec.format.size():colour_plan.linear()?colour_plan.sample_bytes:input_plan.sample_bytes}, + {"source_pixel_bytes",bounded_gray?bounded_source->pixel_bytes:colour_plan.linear()?channels.size()*colour_plan.sample_bytes:input_plan.pixel_bytes}, {"source_buffer_bytes",sampled?sampled->peak_bytes:0}, {"deep_buffer_bytes",deep?job.options.max_decode_mib*1024ULL*1024ULL:0}, - {"cms_buffer_bytes",use_icc?detail::cms_reservation:0}, + {"cms_buffer_bytes",cms_bytes}, {"native_categorical",categorical},{"srgb8",fast_srgb},{"integer_linear",integer_linear},{"c2_stream",c2_active}, + {"source_codec_bytes",source_codec_bytes}, + {"bounded_read",bounded_source?Json{{"pixel_bytes",bounded_source->pixel_bytes},{"retained_bytes",bounded_source->retained_bytes}, + {"transpose",transpose}}:Json()}, {"output_width",largest_w},{"output_height",largest_h},{"threads",job.options.threads}}}, {"sequence_pin",sequence_lock(job.sequence_id)}}; impl_->control.planned(job,plan); @@ -644,24 +847,18 @@ Json Engine::convert(const Job& job) { std::string working_space,input_space,output_space; if(!data) { stage="colour"; - const bool embedded_icc=container_icc || spec.find_attribute("ICCProfile"); if(embedded_icc && job.options.input_space=="auto" && !use_icc) throw Failure("colour_input_unsupported","ICC is unsupported on this input format or Deep input"); if(embedded_icc && !use_icc) r["warnings"].push_back("embedded ICC profile bypassed by explicit input_space; no ICC transform or profile validation performed"); - std::string config_name=job.options.ocio_config,config_basis="explicit"; - if(config_name.empty()) { - const char* environment=std::getenv("OCIO"); - config_name=environment?environment:"";config_basis="environment"; - if(config_name.empty()){config_name="ocio://default";config_basis="builtin";} - } r["colour"]={{"ocio_config",config_name},{"config_basis",config_basis}, {"input_requested",job.options.input_space},{"display",job.options.display},{"view",job.options.view}}; TG_EXR_TICK(config_lookup_tick); #if defined(THUMBGEN_EXR_PROFILE) && THUMBGEN_EXR_PROFILE const bool reused_config=impl_->configs.find(config_name)!=impl_->configs.end(); #endif - config=impl_->config(config_name); + auto& config_entry=impl_->config(config_name); + config=&config_entry.colour; #if defined(THUMBGEN_EXR_PROFILE) && THUMBGEN_EXR_PROFILE profile.add(reused_config?"exr_ocio_config_reuse_ms":"exr_ocio_config_create_ms",config_lookup_tick); #endif @@ -678,27 +875,22 @@ Json Engine::convert(const Job& job) { throw Failure("colour_working_space_invalid","scene_linear role must use a linear colour space"); std::string from=job.options.input_space,basis="explicit"; if(use_icc) { - from=std::string(config->resolve("srgb_rec709_scene"));basis="embedded_icc"; - // Custom configs must explicitly declare this standardized - // scene sRGB bridge; arbitrary scene_linear is never relabeled. - bool declared=config_name=="ocio://default"; - for(int i=0;igetNumColorSpaces();++i) - declared=declared || std::string(config->getColorSpaceNameByIndex(i))=="srgb_rec709_scene"; - if(!declared || from.empty() || config->get_color_interop_id(from)!="srgb_rec709_scene") - throw Failure("colour_input_unsupported","ICC requires a declared standard srgb_rec709_scene OCIO bridge"); + if(config_entry.icc_bridge.empty())config_entry.icc_bridge=resolve_icc_bridge(*config,config_name); + from=config_entry.icc_bridge;basis="embedded_icc"; } else if(from=="auto") { from=spec.get_string_attribute("oiio:ColorSpace");basis="metadata"; if(from.empty()) { auto ext=fs::u8path(job.input).extension().u8string(); std::transform(ext.begin(),ext.end(),ext.begin(),[](unsigned char c){return char(std::tolower(c));}); - from=ext==".exr"||ext==".hdr"?"linear":"sRGB";basis="format_assumption"; + from=input_format=="openexr"||input_format=="hdr"||ext==".exr"||ext==".hdr"?"linear":"sRGB";basis="format_assumption"; r["warnings"].push_back("input colour space assumed from format; override with input_space"); } } input_space=space(from); if(deep && (!config->isColorSpaceLinear(input_space) || spec.get_int_attribute("oiio:UnassociatedAlpha",0))) throw Failure("deep_colour_unsupported","Deep flattening requires associated samples in a verified linear input space"); - if(job.options.display.empty())output_space=space("sRGB"); + if(job.options.display.empty()) + output_space=use_icc && config->getColorSpaceIndex("sRGB")<0?input_space:space("sRGB"); else { const auto displays=config->getDisplayNames(); if(std::find(displays.begin(),displays.end(),job.options.display)==displays.end()) @@ -728,7 +920,7 @@ Json Engine::convert(const Job& job) { } r["colour"]["working_space"]=working_space; r["colour"]["processing"]=c2_active?"integer-linear-stream-v1":colour_plan.processing(); - if(!colour_plan.fallback.empty())r["colour"]["fallback_reason"]=colour_plan.fallback; + if(!bounded_source && !colour_plan.fallback.empty())r["colour"]["fallback_reason"]=colour_plan.fallback; if(use_icc)r["colour"]["icc"]={{"engine","LittleCMS2 2.20"},{"intent","relative_colorimetric"},{"black_point_compensation",false}, {"model",cmyk?"CMYK":chosen.candidate.kind=="grey"?"Gray":"RGB"}, {"bridge","srgb_rec709_scene"},{"profile_limit_bytes",detail::icc_profile_limit},{"cms_limit_bytes",detail::cms_memory_limit}, @@ -753,7 +945,146 @@ Json Engine::convert(const Job& job) { std::unique_ptr exr_pixels; #endif detail::DeepImage deep_image; - if(integer_linear) { + if((jpeg || deferred_other) && !bounded_source){ + jpeg.reset(); + open_input(); + OIIO::ImageSpec reopened; + if(!in->seek_subimage(part,0,reopened) || reopened.width!=spec.width || reopened.height!=spec.height || + reopened.channelnames!=spec.channelnames || reopened.format!=spec.format || + reopened.get_int_attribute("Orientation",1)!=orientation || + reopened.get_int_attribute("oiio:UnassociatedAlpha",0)!=int(straight_alpha)) + throw Failure("decode_failed","source layout changed after admission"); + // Keep plugin metadata for the complete-image path. + spec=std::move(reopened); + } + if(integer_linear && use_icc) { + const auto* profile=spec.find_attribute("ICCProfile");detail::CmsStats stats; + try { + if(!profile)throw detail::CmsFailure("missing ICC profile after admission"); + {detail::CmsInput validate(profile->data(),std::size_t(profile->datasize()),detail::CmsModel::rgb,stats);} + if(stats.live)throw detail::CmsFailure("CMS allocation ledger did not return to zero"); + } catch(const detail::CmsFailure& e){throw Failure("colour_input_unsupported",e.what());} + r["colour"]["icc"]["engine"]="skcms";r["colour"]["icc"]["peak_bytes"]=stats.peak; + } + if(streaming) { + stage="decode"; + order=channels; + const int components=int(channels.size()); + double decode_ms=0,colour_ms=0; + try { + detail::CmsStats stats; + std::unique_ptr cms; + if(use_icc && !integer_linear){ + const auto* profile=spec.find_attribute("ICCProfile"); + if(!profile)throw detail::CmsFailure("missing or invalid embedded ICC profile"); + cms=std::make_unique(profile->data(),std::size_t(profile->datasize()), + bounded_gray?detail::CmsModel::grey:detail::CmsModel::rgb,stats); + } + OIIO::ColorProcessorHandle processor; + if(!colour_plan.linear() && input_space!=working_space) { + processor=config->createColorProcessor(input_space,working_space); + if(!processor)throw Failure("colour_failed","failed to create the bounded colour processor"); + } + auto open_tick=Clock::now(); + if((exr || (bounded_source && input_format=="tiff")) && in)in.reset(); + auto native=bounded_source?bounded_source->open():nullptr; + decode_ms+=ms(open_tick); + const auto pixel_bytes=bounded_source?bounded_source->pixel_bytes:spec.nchannels*colour_plan.sample_bytes; + const auto row_width=spec.full_width,row_height=spec.full_height; + detail::C2PngRows rows(row_width,row_height,components,pixel_bytes, + [&](int first,int last,void* destination){ + detail::output_fault("read",std::size_t(first)); + auto start=Clock::now(); + if(native)native->read(first,last,destination); + else if(!in->read_scanlines(part,0,first,last,0,0,spec.nchannels,spec.format,destination)) + throw Failure("decode_failed",in->geterror()); + decode_ms+=ms(start); + }, + [&](const void* source,float* out,std::size_t count){ + auto start=Clock::now(); + if(exr)detail::exr_rows_to_linear(*exr,processor,source,out,count); + else if(integer_linear)colour_plan.transform(source,out,count,components); + else if(fast_srgb) { + detail::c2_srgb8_to_linear(source,out,count*components); + if(components==4) { + const auto* bytes=static_cast(source); + for(std::size_t i=0;i(source,out,count,components); + else gray_rows_to_rgb(source,out,count,components); + } else if(!OIIO::convert_pixel_values(spec.format,source,OIIO::TypeDesc::FLOAT,out,int(count*components))) + throw Failure("decode_failed","cannot convert native colour block to float"); + if(cms)cms->apply(out,count,components,components==4 && !straight_alpha); + detail::linearize_rows(processor,out,count,components,straight_alpha); + } + colour_ms+=ms(start); + }); + std::exception_ptr source_error; + try { + if(impl_->observer)impl_->observer("c2_allocate",job); + c2_previews.resize(c2_sizes.size()); + c2_output_errors.resize(c2_sizes.size()); + std::vector previews(c2_sizes.size()); + for(std::size_t i=0;i(c2_previews[i].localpixels()); + if(!previews[i])throw std::bad_alloc(); + detail::output_fault("resize",i); + } catch(...) {c2_output_errors[i]=std::current_exception();} + } + detail::C2Resize resize(row_width,row_height,components,c2_sizes,c2_workspace_bytes,&c2_output_errors); + detail::output_fault("invariant",0); + c2_resize_ms=resize.execute([&](int y,float* row){ + try {rows.get(y,row);}catch(...){source_error=std::current_exception();throw;} + detail::output_fault("resize_row",std::size_t(y)); + },previews); + } catch(const detail::C2PlanLimit&) {throw;} + catch(const detail::C2ContractError&) {throw;} + catch(const std::bad_alloc&) { + if(source_error)std::rethrow_exception(source_error); + c2_preview_error=std::make_exception_ptr(Failure("resize_failed","linear float resize failed")); + c2_previews.clear(); + } + catch(...) { + if(source_error)std::rethrow_exception(source_error); + c2_preview_error=std::current_exception(); + c2_previews.clear(); + } + // Always complete the source once. Decode and colour errors + // still take precedence over deferred output failures. + rows.finish(); + auto finish_tick=Clock::now(); + if(native)native->finish(); + if(in)in->close(); + decode_ms+=ms(finish_tick); + cms.reset(); + if(stats.live)throw detail::CmsFailure("CMS allocation ledger did not return to zero"); + if(use_icc && !integer_linear)r["colour"]["icc"]["peak_bytes"]=stats.peak; + if(jpeg)jpeg->read.open={}; + r["decoded_mib"]=double(std::uint64_t(row_width)*row_height*pixel_bytes)/1048576; + }catch(const detail::CmsFailure& error){throw Failure("colour_input_unsupported",error.what());} + if(impl_->observer)impl_->observer("decoded",job); + verify_source(); + r["timings_ms"]["decode"]=decode_ms;r["timings_ms"]["input_colour"]=colour_ms; + } else if(integer_linear) { stage="decode";tick=Clock::now(); const std::size_t budget=job.options.max_decode_mib*1024ULL*1024ULL; const std::size_t reservation=use_icc?detail::cms_reservation:0; @@ -761,68 +1092,9 @@ Json Engine::convert(const Job& job) { // before allocation. Reference ICC validation fits the same reserve. const std::size_t per_pixel=channels.size()*(colour_plan.sample_bytes+2*sizeof(float)); std::size_t count=std::size_t(spec.width); - if(!c2_active && (reservation>budget || count>(budget-reservation)/per_pixel/std::size_t(spec.height))) + if(reservation>budget || count>(budget-reservation)/per_pixel/std::size_t(spec.height)) throw Failure("decode_limit_exceeded","native colour source and linear buffers exceed decode budget"); count*=std::size_t(spec.height); - if(use_icc) { - const auto* profile=spec.find_attribute("ICCProfile");detail::CmsStats stats; - try {{detail::CmsInput validate(profile->data(),std::size_t(profile->datasize()),detail::CmsModel::rgb,stats);} - if(stats.live)throw detail::CmsFailure("CMS allocation ledger did not return to zero");} - catch(const detail::CmsFailure& e){throw Failure("colour_input_unsupported",e.what());} - r["colour"]["icc"]["engine"]="skcms";r["colour"]["icc"]["peak_bytes"]=stats.peak; - } -#ifdef THUMBGEN_C2_PNG_STREAM - if(c2_active){ - order=channels; - double decode_ms=0,colour_ms=0; - try{ - detail::C2PngRows rows(spec.width,spec.height,spec.nchannels,colour_plan, - [&](int first,int last,void* data){detail::output_fault("read",std::size_t(first));auto start=Clock::now();bool ok=in->read_scanlines(part,0,first,last,0,0,spec.nchannels,spec.format,data);decode_ms+=ms(start);if(!ok)throw Failure("decode_failed",in->geterror());}, - [&](const void* data,float* out,std::size_t n){auto start=Clock::now();colour_plan.transform(data,out,n,spec.nchannels);colour_ms+=ms(start);}); - std::exception_ptr source_error; - try { - // All allocations remain after planned/admission. Resize - // failures belong to the later per-output try/catch; - // source failures must still take job-level precedence. - if(impl_->observer)impl_->observer("c2_allocate",job); - c2_previews.reserve(1); - auto [w,h]=c2_sizes.front(); - auto linear=spec;linear.set_format(OIIO::TypeDesc::FLOAT);linear.erase_attribute("ICCProfile");linear.attribute("oiio:UnassociatedAlpha",0); - linear.x=linear.y=linear.z=linear.full_x=linear.full_y=linear.full_z=0; - linear.width=linear.full_width=w;linear.height=linear.full_height=h;linear.depth=linear.full_depth=1; - detail::output_fault_index(0); - c2_previews.emplace_back(detail::preview_storage(linear)); - if(!c2_previews.back().localpixels())throw Failure("resize_failed","linear float resize failed"); - try { - c2_resize=std::make_unique(spec.width,spec.height,spec.nchannels,c2_sizes); - if(c2_resize->workspace_bytes()!=c2_workspace_bytes)throw detail::C2ContractError("C2 admitted workspace differs from allocation"); - detail::output_fault("invariant",0); - detail::output_fault("resize",0); - c2_resize_ms=c2_resize->execute([&](int y,float* data){ - try {rows.get(y,data);}catch(...){source_error=std::current_exception();throw;} - detail::output_fault("resize_row",std::size_t(y)); - },{static_cast(c2_previews.front().localpixels())}); - } catch(const std::bad_alloc&) { - if(source_error)std::rethrow_exception(source_error); - throw Failure("resize_failed","linear float resize failed"); - } - } catch(const detail::C2PlanLimit&) {throw;} - catch(const detail::C2ContractError&) {throw;} - catch(...) { - if(source_error)std::rethrow_exception(source_error); - c2_preview_error=std::current_exception(); - c2_previews.clear(); - } - c2_resize.reset(); - // Even when resize failed before reading anything, consume - // the source exactly once with original colour block/tail - // calls. Decode/ICC/source failures outrank output failures. - rows.finish(); - }catch(const detail::CmsFailure& error){throw Failure("colour_input_unsupported",error.what());} - in->close();if(impl_->observer)impl_->observer("decoded",job);verify_source(); - r["timings_ms"]["decode"]=decode_ms;r["timings_ms"]["input_colour"]=colour_ms; - }else -#endif if(scanline_png) { auto linear=spec;linear.set_format(OIIO::TypeDesc::FLOAT);linear.erase_attribute("ICCProfile");linear.attribute("oiio:UnassociatedAlpha",0); working.reset(linear);order=channels; @@ -1008,7 +1280,7 @@ Json Engine::convert(const Job& job) { const size_t limit=job.options.max_decode_mib*1024ULL*1024ULL/sizeof(float); // resize() clamps outside the data window. Pad a cropped display window // with zero pixels first, rather than stretching edge pixels into it. - if(!categorical && !c2_active) { + if(!categorical && !streaming) { const auto& window=working.spec(); if(window.x!=window.full_x || window.y!=window.full_y || window.width!=window.full_width || window.height!=window.full_height) { @@ -1028,15 +1300,15 @@ Json Engine::convert(const Job& job) { } // Orient a complete, zero-origin display canvas. Some OIIO rotations // position cropped data incorrectly when the full window has an origin. - if(!categorical && !c2_active){working.set_origin(0,0,0);working.set_roi_full(working.roi());} - if(!categorical && spec.get_int_attribute("Orientation",1)!=1) { + if(!categorical && !streaming){working.set_origin(0,0,0);working.set_roi_full(working.roi());} + if(!categorical && !streaming && orientation!=1) { OIIO::ImageBuf oriented; check(iba::reorient(oriented,working),oriented,"orientation_failed");working=std::move(oriented); } TG_EXR_TOCK(canvas_tick,"exr_canvas_orientation_ms"); stage="colour";tick=Clock::now(); TG_EXR_TICK(working_tick); - if(!data && !colour_plan.linear() && input_space!=working_space) + if(!data && !streaming && !colour_plan.linear() && input_space!=working_space) check(iba::colorconvert(working,working,input_space,working_space,true,"","",config),working,"colour_failed"); TG_EXR_TOCK(working_tick,"exr_ocio_working_apply_ms"); r["timings_ms"]["working_colour"]=ms(tick); @@ -1056,22 +1328,27 @@ Json Engine::convert(const Job& job) { r["outputs"].push_back(result);continue; } verify_source(); - int display_width=(categorical || c2_active)?spec.full_width:working.spec().full_width; - int display_height=(categorical || c2_active)?spec.full_height:working.spec().full_height; - if(categorical && spec.get_int_attribute("Orientation",1)>=5 && spec.get_int_attribute("Orientation",1)<=8)std::swap(display_width,display_height); - double scale=std::min({double(out.width)/display_width,double(out.height)/display_height,1.0}); - int w=std::max(1,int(std::lround(display_width*scale))),h=std::max(1,int(std::lround(display_height*scale))); + int display_width=(categorical || streaming)?spec.full_width:working.spec().full_width; + int display_height=(categorical || streaming)?spec.full_height:working.spec().full_height; + if((categorical || streaming) && transpose)std::swap(display_width,display_height); + const auto [w,h]=detail::fit_preview(display_width,display_height,out.width,out.height); OIIO::ImageBuf preview; tick=Clock::now(); TG_EXR_TICK(resize_tick); -#ifdef THUMBGEN_C2_PNG_STREAM - if(c2_active){ + if(streaming){ if(c2_preview_error)std::rethrow_exception(c2_preview_error); - preview=std::move(c2_previews.front()); - } - else -#endif - if(fast_srgb) + if(c2_output_errors[output_index]) { + try {std::rethrow_exception(c2_output_errors[output_index]);} + catch(const std::bad_alloc&){throw Failure("resize_failed","linear float resize failed");} + } + preview=std::move(c2_previews[output_index]); + if(orientation!=1){ + preview.specmod().attribute("Orientation",orientation); + OIIO::ImageBuf oriented; + check(iba::reorient(oriented,preview),oriented,"orientation_failed"); + preview=std::move(oriented); + } + } else if(fast_srgb) preview=detail::resize_srgb8(working,w,h); else if(integer_linear){ detail::output_fault_index(output_index); @@ -1084,9 +1361,7 @@ Json Engine::convert(const Job& job) { else check(iba::resize(preview,working,{{"filtername",filter}},OIIO::ROI(0,w,0,h,0,1,0,int(order.size())),job.options.threads),preview,"resize_failed"); TG_EXR_TOCK(resize_tick,"exr_resize_sum_ms"); result["resize_ms"]=ms(tick);tick=Clock::now(); -#ifdef THUMBGEN_C2_PNG_STREAM - if(c2_active)result["resize_ms"]=c2_resize_ms[output_index]; -#endif + if(streaming)result["resize_ms"]=c2_resize_ms[output_index]; TG_EXR_TICK(finish_tick); if(job.options.background!="transparent" && preview.nchannels()==4) { OIIO::ImageSpec bs(w,h,4,OIIO::TypeDesc::FLOAT);bs.alpha_channel=3; diff --git a/src/cryptomatte.cpp b/src/cryptomatte.cpp index 04766ca..a574615 100644 --- a/src/cryptomatte.cpp +++ b/src/cryptomatte.cpp @@ -34,6 +34,10 @@ std::vector crypto_names(const OIIO::ImageSpec& spec) { } return {names.begin(),names.end()}; } +bool is_object_crypto_family(const std::string& name) { + const auto normalized=lower(name); + return normalized=="crypto_object" || normalized=="cryptoobject"; +} bool crypto_group(const std::vector& names,const std::string& group) { return std::any_of(names.begin(),names.end(),[&](const auto& name){return group==name || (group.rfind(name,0)==0 && digits(group.substr(name.size())));}); } diff --git a/src/cryptomatte.h b/src/cryptomatte.h index 5d69ad1..7211ff1 100644 --- a/src/cryptomatte.h +++ b/src/cryptomatte.h @@ -15,6 +15,7 @@ struct CryptoLayout { // Lightweight semantic classification; malformed optional crypto metadata must // not block an unrelated Beauty conversion. std::vector crypto_names(const OIIO::ImageSpec& spec); +bool is_object_crypto_family(const std::string& name); bool crypto_group(const std::vector& names,const std::string& group); CryptoLayout crypto_layout(std::vector specs,const std::string& family,int selected_part=-1); std::size_t crypto_source_pixel_bytes(const CryptoLayout& layout); diff --git a/src/dpx_rows.cpp b/src/dpx_rows.cpp new file mode 100644 index 0000000..141632b --- /dev/null +++ b/src/dpx_rows.cpp @@ -0,0 +1,47 @@ +#include "other_rows_internal.h" + +namespace thumbgen::detail::other_rows { +OtherRowsProbe dpx(Source& source) { + constexpr std::uint64_t header_size=2048; + std::array header{}; + source.read(0,header.data(),header.size(),"truncated DPX header"); + const bool little=is(header.data(),"XPDS"); + const auto u16=[&](int p){return little?le16(header.data()+p):unsigned(header[p])*256+header[p+1];}; + const auto u32=[&](int p){ + return little?le32(header.data()+p):std::uint32_t(u16(p))*65536+u16(p+2); + }; + const auto orientation=u16(768),elements=u16(770); + const auto width=u32(orientation>=4 && orientation<=7?776:772); + const auto height=u32(orientation>=4 && orientation<=7?772:776); + const auto pixels=dimensions(width,height,65536,"DPX dimensions exceed supported limits"); + require(elements>0 && elements<=8,"invalid DPX element count"); + const auto user=u32(32)==std::uint32_t(-1)?0:u32(32); + source.extent(header_size,user,"truncated DPX user metadata"); + reserve(user,metadata_limit,"DPX user metadata exceeds limit"); + const auto codec=plugin_bytes+metadata_copies*user+16*std::uint64_t(width); + reserve(codec,source.budget,"DPX header and codec scratch exceed decode budget"); + + const unsigned bits=header[803],packing=u16(804),encoding=u16(806); + const auto row_padding=u32(812); + const bool rgb=elements==1 && !u32(780) && header[800]==50 && orientation<=7 && + encoding==0 && packing<=2 && (row_padding==0 || row_padding==std::uint32_t(-1)); + if(!rgb || (bits!=8 && bits!=10 && bits!=12 && bits!=16)) { + // Complete-image reads may use an intermediate component conversion + // buffer or unpacker. Bound all elements before invoking the plugin. + const auto scratch=std::uint64_t(elements)*pixels*8*8; + reserve(source.size,std::numeric_limits::max(),"DPX source exceeds decoder offset range"); + return fallback(source,"dpx",pixels,codec+scratch); + } + + std::uint64_t stride=std::uint64_t(width)*(bits==8?3:6); + if(bits==10 && packing!=0)stride=std::uint64_t(width)*4; + else if((bits==10 || bits==12) && packing==0)stride=(std::uint64_t(width)*3*bits+31)/32*4; + const auto offset=u32(808); + require(offset>=header_size+user,"invalid DPX data offset"); + source.extent(offset,stride*height,"truncated DPX image data"); + // libdpx's element stream uses a signed long for offsets on Windows. + reserve(offset+stride*height,std::numeric_limits::max(),"DPX image data exceeds decoder offset range"); + auto spec=metadata(source,"dpx"); + return supported(source,"dpx",std::move(spec),0,codec); +} +} diff --git a/src/exr_rows.cpp b/src/exr_rows.cpp new file mode 100644 index 0000000..e8154f6 --- /dev/null +++ b/src/exr_rows.cpp @@ -0,0 +1,365 @@ +#include "exr_rows.h" +#include "files.h" +#include +#include +#include +#include +#include +#include +#include +#include + +namespace thumbgen::detail { +namespace { +constexpr int dimension_limit=65536; +constexpr int channel_limit=4096; +constexpr std::size_t metadata_limit=8*bounded_mib; +constexpr std::size_t chunk_limit=64*bounded_mib; +constexpr int chunk_count_limit=1024*1024; // OpenEXR Core's offset table limit. + +// Core's allocator has no userdata. Each context is used synchronously and +// each allocation records its owner so that frees can occur outside its scope. +struct Ledger {std::size_t limit=metadata_limit,used=0;bool denied=false;}; +thread_local Ledger* active_ledger=nullptr; +struct AllocationScope { + Ledger* previous; + explicit AllocationScope(Ledger& owner):previous(std::exchange(active_ledger,&owner)){} + ~AllocationScope(){active_ledger=previous;} +}; +struct alignas(std::max_align_t) Allocation {Ledger* owner;std::size_t bytes;}; +void* allocate(std::size_t bytes) noexcept { + if(!active_ledger)return nullptr; + auto& ledger=*active_ledger; + const auto available=ledger.limit-ledger.used; + if(availableavailable-sizeof(Allocation)) { + ledger.denied=true; + return nullptr; + } + const auto total=sizeof(Allocation)+bytes; + void* raw=std::malloc(total); + if(!raw)return nullptr; + ledger.used+=total; + return new(raw) Allocation{&ledger,total}+1; +} +void release(void* ptr) noexcept { + if(!ptr)return; + auto* allocation=static_cast(ptr)-1; + allocation->owner->used-=allocation->bytes; + std::free(allocation); +} +void quiet_error(exr_const_context_t,exr_result_t,const char*) noexcept {} +struct Context { + Ledger ledger; + exr_context_t value=nullptr; + Context()=default; + Context(const Context&)=delete; + Context& operator=(const Context&)=delete; + ~Context(){if(value)exr_finish(&value);} + exr_result_t open(const std::string& path,int max_dimension=dimension_limit) { + exr_context_initializer_t options=EXR_DEFAULT_CONTEXT_INITIALIZER; + options.alloc_fn=&allocate; + options.free_fn=&release; + options.error_handler_fn=&quiet_error; + options.flags=EXR_CONTEXT_FLAG_DISABLE_CHUNK_RECONSTRUCTION; + options.max_image_width=max_dimension; + options.max_image_height=max_dimension; + options.max_tile_width=max_dimension; + options.max_tile_height=max_dimension; + AllocationScope scope(ledger); + return exr_start_read(&value,path.c_str(),&options); + } + void check(exr_result_t status) const { + if(status==EXR_ERR_SUCCESS)return; + if(ledger.denied)throw FileFailure("decode_limit_exceeded","OpenEXR decoder exceeded its reserved memory"); + throw FileFailure("decode_failed",exr_get_error_code_as_string(status)); + } +}; + +struct Window { + int x,y,w,h; + int end_x() const {return x+w;} + int end_y() const {return y+h;} + bool valid() const { + return w>0 && h>0 && w<=dimension_limit && h<=dimension_limit && + std::int64_t(x)+w<=std::numeric_limits::max() && + std::int64_t(y)+h<=std::numeric_limits::max(); + } + bool matches(const exr_attr_box2i_t& box) const { + return box.min.x==x && box.min.y==y && box.max.x==end_x()-1 && box.max.y==end_y()-1; + } +}; +struct Selection { + Window data,display; + int part,channel_count,tile_width,tile_height,components; + exr_pixel_type_t sample; + std::array names; +}; +struct Layout { + exr_storage_t storage; + exr_compression_t compression; + int block_width,block_height; + int first_tile=0,last_tile=-1,strip_x=0,strip_width=0; + int copy_x,copy_y,copy_end_x,copy_end_y; + std::array lanes{{-1,-1,-1,-1}}; + unsigned pixel_bytes,all_pixel_bytes=0; + std::uint64_t retained_bytes=0,codec_bytes=0; +}; + +std::optional inspect(exr_const_context_t context,const Selection& selected) { + Layout layout{}; + exr_attr_box2i_t data{},display{}; + const exr_attr_chlist_t* channels=nullptr; + int32_t chunks=0; + const int part=selected.part; + if(exr_get_storage(context,part,&layout.storage)!=EXR_ERR_SUCCESS || + exr_get_compression(context,part,&layout.compression)!=EXR_ERR_SUCCESS || + exr_get_data_window(context,part,&data)!=EXR_ERR_SUCCESS || + exr_get_display_window(context,part,&display)!=EXR_ERR_SUCCESS || + exr_get_chunk_count(context,part,&chunks)!=EXR_ERR_SUCCESS || + exr_get_channels(context,part,&channels)!=EXR_ERR_SUCCESS || + !selected.data.matches(data) || !selected.display.matches(display) || + channels->num_channels!=selected.channel_count || chunks<=0 || chunks>chunk_count_limit)return {}; + + switch(layout.compression) { + case EXR_COMPRESSION_NONE: + case EXR_COMPRESSION_RLE: + case EXR_COMPRESSION_ZIPS: + case EXR_COMPRESSION_ZIP: + case EXR_COMPRESSION_PIZ: break; + default: return {}; + } + if(layout.storage==EXR_STORAGE_SCANLINE) { + int32_t lines=0; + if(selected.tile_width || selected.tile_height || + exr_get_scanlines_per_chunk(context,part,&lines)!=EXR_ERR_SUCCESS || + lines<1 || lines>32)return {}; + layout.block_width=selected.data.w; + layout.block_height=lines; + } else if(layout.storage==EXR_STORAGE_TILED) { + uint32_t tw=0,th=0; + exr_tile_level_mode_t mode; + exr_tile_round_mode_t round; + if(exr_get_tile_descriptor(context,part,&tw,&th,&mode,&round)!=EXR_ERR_SUCCESS || + mode!=EXR_TILE_ONE_LEVEL || !tw || !th || + tw!=unsigned(selected.tile_width) || th!=unsigned(selected.tile_height))return {}; + layout.block_width=int(tw); + layout.block_height=int(th); + } else return {}; + + const auto& d=selected.data; + const auto& f=selected.display; + const auto nx=(std::uint64_t(d.w)+layout.block_width-1)/layout.block_width; + const auto ny=(std::uint64_t(d.h)+layout.block_height-1)/layout.block_height; + if(std::uint64_t(chunks)!=nx*ny)return {}; + + for(int c=0;cnum_channels;++c) { + const auto& channel=channels->entries[c]; + if(channel.x_sampling!=1 || channel.y_sampling!=1)return {}; + layout.all_pixel_bytes+=channel.pixel_type==EXR_PIXEL_HALF?2:4; + for(int i=0;ichunk_limit)return {}; + + layout.copy_x=std::max(d.x,f.x); + layout.copy_end_x=std::min(d.end_x(),f.end_x()); + layout.copy_y=std::max(d.y,f.y); + layout.copy_end_y=std::min(d.end_y(),f.end_y()); + layout.codec_bytes=metadata_limit; + if(layout.copy_x>=layout.copy_end_x || layout.copy_y>=layout.copy_end_y)return layout; + layout.first_tile=(layout.copy_x-d.x)/layout.block_width; + layout.last_tile=(layout.copy_end_x-1-d.x)/layout.block_width; + layout.strip_x=d.x+layout.first_tile*layout.block_width; + layout.strip_width=std::min(d.w,(layout.last_tile+1)*layout.block_width)-(layout.strip_x-d.x); + // Guard the codec's interleave detection pointer arithmetic. Only the + // interior strip is written, using coordinates relative to its origin. + layout.retained_bytes=std::uint64_t(layout.strip_width)*block_rows*layout.pixel_bytes+ + 2*std::uint64_t(channels->num_channels)*sample_bytes; + if(layout.retained_bytes>std::numeric_limits::max())return {}; + // Core keeps only the selected part's offset table. A compressed chunk + // can need packed, unpacked and shuffle buffers for *all* source lanes. + // The fixed codec allowance covers channel descriptors, allocator headers, + // libdeflate state, and both PIZ Huffman scratch tables and lookup lists. + const auto block_copies=layout.compression==EXR_COMPRESSION_NONE?1:3; + layout.codec_bytes+=std::uint64_t(chunks)*sizeof(std::uint64_t)+max_chunk*block_copies+4*bounded_mib; + return layout; +} + +class ExrRows final:public NativeRowSource { + Context context_; + Selection selection_; + Layout layout_; + exr_decode_pipeline_t pipeline_=EXR_DECODE_PIPELINE_INITIALIZER; + std::vector strip_; + bool initialized_=false; + int next_=0,cached_block_=-1; + + void load(int block) { + const auto& s=selection_; + const auto& l=layout_; + const auto row_bytes=std::size_t(l.strip_width)*l.pixel_bytes; + const unsigned sample_bytes=l.pixel_bytes/s.components; + const auto guard=std::size_t(s.channel_count)*sample_bytes; + const auto local_y=block*l.block_height; + const auto height=std::min(l.block_height,s.data.h-local_y); + AllocationScope scope(context_.ledger); + for(int tile=l.first_tile;tile<=l.last_tile;++tile) { + exr_chunk_info_t chunk{}; + const auto local_x=tile*l.block_width; + const auto width=std::min(l.block_width,s.data.w-local_x); + const bool tiled=l.storage==EXR_STORAGE_TILED; + if(tiled)context_.check(exr_read_tile_chunk_info(context_.value,s.part,tile,block,0,0,&chunk)); + else context_.check(exr_read_scanline_chunk_info(context_.value,s.part,s.data.y+local_y,&chunk)); + if(chunk.start_x!=(tiled?tile:s.data.x) || chunk.start_y!=(tiled?block:s.data.y+local_y) || + chunk.width!=width || chunk.height!=height || chunk.type!=l.storage || chunk.compression!=l.compression || + chunk.unpacked_size!=std::uint64_t(width)*height*l.all_pixel_bytes || + !chunk.packed_size || chunk.packed_size>chunk.unpacked_size) + throw FileFailure("decode_failed","OpenEXR chunk does not match the admitted layout"); + + if(!initialized_) { + context_.check(exr_decoding_initialize(context_.value,s.part,&chunk,&pipeline_)); + initialized_=true; + } else context_.check(exr_decoding_update(context_.value,s.part,&chunk,&pipeline_)); + const auto offset=guard+std::size_t(local_x-(l.strip_x-s.data.x))*l.pixel_bytes; + for(int i=0;icompression!=plan.compression || layout->retained_bytes>plan.retained_bytes || + layout->codec_bytes>plan.codec_bytes) + throw FileFailure("decode_failed","OpenEXR layout changed after admission"); + layout_=*layout; + context_.ledger.limit=std::size_t(plan.codec_bytes); + strip_.resize(std::size_t(layout_.retained_bytes)); + } + ~ExrRows() override { + if(initialized_)exr_decoding_destroy(context_.value,&pipeline_); + } + void read(int first,int last,void* destination) override { + const auto& s=selection_; + const auto& l=layout_; + if(first!=next_ || first<0 || first>=last || last>s.display.h || !destination) + throw FileFailure("decode_failed","OpenEXR rows must be read once in order"); + auto* out=static_cast(destination); + const auto row_bytes=std::size_t(s.display.w)*l.pixel_bytes; + const auto guard=std::size_t(s.channel_count)*(l.pixel_bytes/s.components); + for(;next_=l.copy_end_x || y=l.copy_end_y) { + std::memset(out,0,row_bytes); + continue; + } + const auto local_y=y-s.data.y; + const auto block=local_y/l.block_height; + if(block!=cached_block_)load(block); + const auto input_pixel=std::size_t(local_y%l.block_height)*l.strip_width+(l.copy_x-l.strip_x); + const auto left_bytes=std::size_t(l.copy_x-s.display.x)*l.pixel_bytes; + const auto copy_bytes=std::size_t(l.copy_end_x-l.copy_x)*l.pixel_bytes; + std::memset(out,0,left_bytes); + std::memcpy(out+left_bytes,strip_.data()+guard+input_pixel*l.pixel_bytes,copy_bytes); + std::memset(out+left_bytes+copy_bytes,0,row_bytes-left_bytes-copy_bytes); + } + } + void finish() override { + if(next_!=selection_.display.h)throw FileFailure("decode_failed","incomplete OpenEXR display rows"); + } +}; +} + +bool preflight_exr_header(const std::string& path) { + constexpr std::array signature{{0x76,0x2f,0x31,0x01}}; + std::array magic{}; + std::ifstream input(std::filesystem::u8path(path),std::ios::binary); + if(!input.read(reinterpret_cast(magic.data()),magic.size()) || magic!=signature)return false; + Context context; + context.open(path,0); + if(context.ledger.denied) + throw FileFailure("decode_limit_exceeded","OpenEXR metadata exceeds its allocation limit"); + return true; +} + +std::optional probe_exr_rows(const std::string& path,const OIIO::ImageSpec& spec, + int part,const std::vector& channels) { + if(part<0 || spec.deep || spec.depth!=1 || spec.full_depth!=1 || spec.nchannels<3 || + spec.nchannels>channel_limit || (channels.size()!=3 && channels.size()!=4) || + spec.get_int_attribute("openexr:luminancechroma",0))return {}; + Selection selection{{spec.x,spec.y,spec.width,spec.height}, + {spec.full_x,spec.full_y,spec.full_width,spec.full_height},part,spec.nchannels, + spec.tile_width,spec.tile_height,int(channels.size()),EXR_PIXEL_HALF,{}}; + if(!selection.data.valid() || !selection.display.valid())return {}; + OIIO::TypeDesc format; + for(int i=0;i=spec.nchannels || std::size_t(c)>=spec.channelnames.size() || + std::find(channels.begin(),channels.begin()+i,c)!=channels.begin()+i)return {}; + const auto native=spec.channelformat(c); + if(native!=OIIO::TypeDesc::HALF && native!=OIIO::TypeDesc::FLOAT)return {}; + if(i && format!=native)return {}; + format=native; + selection.names[i]=spec.channelnames[c]; + } + selection.sample=format==OIIO::TypeDesc::HALF?EXR_PIXEL_HALF:EXR_PIXEL_FLOAT; + Context context; + if(context.open(path)!=EXR_ERR_SUCCESS)return {}; + const auto layout=inspect(context.value,selection); + if(!layout)return {}; + if(layout->retained_bytes) { + // This reads offsets for the chosen part only. Leave recoverable + // tables to the reference decoder before bounded decode is admitted. + context.ledger.limit=std::size_t(layout->codec_bytes); + AllocationScope scope(context.ledger); + if(exr_validate_chunk_table(context.value,part)!=EXR_ERR_SUCCESS)return {}; + } + return ExrRowProbe{{layout->pixel_bytes,layout->retained_bytes,layout->codec_bytes, + [path,selection,plan=*layout]{return std::make_unique(path,selection,plan);}}, + format,selection.components,spec.get_int_attribute("oiio:UnassociatedAlpha",0)!=0}; +} + +void exr_rows_to_linear(const ExrRowProbe& probe,const OIIO::ColorProcessorHandle& processor, + const void* source,float* destination,std::size_t pixels) { + const auto components=probe.components; + if(!OIIO::convert_pixel_values(probe.sample_format,source,OIIO::TypeDesc::FLOAT,destination,int(pixels*components))) + throw FileFailure("decode_failed","cannot convert native OpenEXR colour block to float"); + linearize_rows(processor,destination,pixels,components,probe.unassociated_alpha); +} + +void linearize_rows(const OIIO::ColorProcessorHandle& processor,float* destination, + std::size_t pixels,int components,bool straight_alpha) { + const bool associate=components==4 && straight_alpha; + if(!associate && (!processor || processor->isNoOp()))return; + // The complete-image path uses ImageBufAlgo's premult and colourconvert + // conventions, including zero-alpha emission and RGB transforms that + // consume a padded fourth lane. Restrict their scratch to short runs. + for(std::size_t i=0;i(pixels-i,2048)); + OIIO::ImageSpec spec(count,1,components,OIIO::TypeDesc::FLOAT); + OIIO::ImageBuf image(spec,destination+i*components); + if(associate && !OIIO::ImageBufAlgo::premult(image,image,{},1)) + throw FileFailure("alpha_failed",image.geterror()); + if(processor && !OIIO::ImageBufAlgo::colorconvert(image,image,processor.get(),true,{},1)) + throw FileFailure("colour_failed",image.geterror()); + i+=count; + } +} +} diff --git a/src/exr_rows.h b/src/exr_rows.h new file mode 100644 index 0000000..7ab3ce6 --- /dev/null +++ b/src/exr_rows.h @@ -0,0 +1,29 @@ +#pragma once +#include "bounded_read.h" +#include +#include +#include +#include +#include + +namespace thumbgen::detail { +bool preflight_exr_header(const std::string& path); + +struct ExrRowProbe { + NativeReadPlan read; + OIIO::TypeDesc sample_format; + int components; + bool unassociated_alpha; +}; + +// The selected part and channel order come from the normal selection policy. +// The factory presents native pixels in display order, with zero pixels +// outside the data window. Requests are relative to the display origin. +std::optional probe_exr_rows(const std::string& path,const OIIO::ImageSpec& spec, + int part,const std::vector& channels); + +void exr_rows_to_linear(const ExrRowProbe& probe,const OIIO::ColorProcessorHandle& processor, + const void* source,float* destination,std::size_t pixels); +void linearize_rows(const OIIO::ColorProcessorHandle& processor,float* pixels, + std::size_t count,int components,bool straight_alpha); +} diff --git a/src/hdr_rows.cpp b/src/hdr_rows.cpp new file mode 100644 index 0000000..1e1f642 --- /dev/null +++ b/src/hdr_rows.cpp @@ -0,0 +1,14 @@ +#include "other_rows_internal.h" + +namespace thumbgen::detail::other_rows { +OtherRowsProbe hdr(Source& source) { + // The plugin reads at most 100 header lines in fixed 128-byte buffers. + // One read at a time allocates 4 bytes/pixel of RGBE scratch. The + // sequential reader also keeps row offsets in a growing vector. + reserve(plugin_bytes,source.budget,"HDR header exceeds decode budget"); + auto spec=metadata(source,"hdr"); + const auto bytes=plugin_bytes+4*std::uint64_t(spec.width)+ + 4*sizeof(std::int64_t)*(std::uint64_t(spec.height)+1); + return supported(source,"hdr",std::move(spec),0,bytes); +} +} diff --git a/src/isolated.cpp b/src/isolated.cpp index 6766e53..e877c03 100644 --- a/src/isolated.cpp +++ b/src/isolated.cpp @@ -1,5 +1,6 @@ #include "isolated.h" #include "budget.h" +#include "c2_resize.h" #include "child_process.h" #include "files.h" #include "worker_protocol.h" @@ -407,7 +408,7 @@ bool run_isolated(const std::vector& jobs,const std::string& executable,con catch(const FileFailure&){throw FileFailure("source_changed","source could not be verified after metadata preparation",true);} if(stamp_json(*source)!=payload["source_stamp"])throw FileFailure("source_changed","source changed during metadata preparation",true); const auto mode=effective_visualization(base,job); - const auto& f=payload["footprint"];fields(f,{"data_width","data_height","display_width","display_height","channel_span","selected_channels","output_width","output_height","threads","source_sample_bytes","source_pixel_bytes","source_buffer_bytes","native_categorical","deep_buffer_bytes","cms_buffer_bytes","srgb8","integer_linear","c2_stream"}); + const auto& f=payload["footprint"];fields(f,{"data_width","data_height","display_width","display_height","channel_span","selected_channels","output_width","output_height","threads","source_sample_bytes","source_pixel_bytes","source_buffer_bytes","native_categorical","deep_buffer_bytes","cms_buffer_bytes","srgb8","integer_linear","c2_stream","source_codec_bytes","bounded_read"}); const bool categorical=job.options.visualization=="id" || job.options.visualization=="id_rgb"; check(f["native_categorical"].is_boolean() && f["native_categorical"]==categorical,"worker categorical footprint mismatch"); check(number(f["threads"],256)==unsigned(job.options.threads),"plan thread quota mismatch"); @@ -434,12 +435,53 @@ bool run_isolated(const std::vector& jobs,const std::string& executable,con check(!srgb8 || (mode=="colour" && job.options.preset=="balanced" && !base.contains("deep") && base.contains("source") && base["source"]["sample_type"]=="uint8"),"invalid sRGB8 processing plan"); check(!shape.cms_buffer_bytes || (mode=="colour" && job.options.input_space=="auto" && !base.contains("deep")),"invalid worker CMS footprint"); + const auto decode_budget=job.options.max_decode_mib*bounded_mib; + shape.source_codec_bytes=number(f["source_codec_bytes"],decode_budget); + const auto& bounded=f["bounded_read"]; + const bool bounded_gray=!bounded.is_null() && base.at("selection").at("chosen").at("kind")=="grey"; + if(!bounded.is_null()){ + fields(bounded,{"pixel_bytes","retained_bytes","transpose"}); + check(mode=="colour" && job.options.preset=="balanced" && job.outputs.size()>=1 && job.outputs.size()<=2 && + !shape.c2_stream && !shape.native_categorical && !shape.deep_buffer_bytes && !shape.source_buffer_bytes && + shape.data_width && shape.data_height && shape.data_width<=65536 && shape.data_height<=65536 && + bounded["transpose"].is_boolean(),"invalid bounded reader footprint"); + const bool transpose=bounded["transpose"].get(); + const auto& source_info=base.at("source"); + const auto& window=source_info.at("display_window"); + check(window.is_array() && window.size()==4 && + shape.data_width==number(source_info.at("width"),65536) && + shape.data_height==number(source_info.at("height"),65536),"bounded source footprint mismatch"); + const auto row_width=number(window[2],65536),row_height=number(window[3],65536); + check(row_width && row_height && shape.display_width==(transpose?row_height:row_width) && + shape.display_height==(transpose?row_width:row_height),"bounded display footprint mismatch"); + std::vector> sizes; + for(const auto& output:job.outputs) + sizes.push_back(fit_preview(int(row_width),int(row_height), + transpose?output.height:output.width,transpose?output.width:output.height)); + std::size_t workspace=0; + check(C2Resize::workspace_plan(int(row_width),int(row_height),int(shape.selected_channels), + sizes,workspace,bounded_sampler_limit), + "invalid bounded sampler footprint"); + const auto bytes=number(bounded["pixel_bytes"],32); + check(bytes>0,"invalid bounded native pixel size"); + if(bounded_gray) { + const auto& sample_type=source_info.at("sample_type"); + check(((shape.source_sample_bytes==1 && sample_type=="uint8") || + (shape.source_sample_bytes==2 && sample_type=="uint16")) && + shape.channel_span+2==shape.selected_channels && + bytes==shape.source_sample_bytes*shape.channel_span && bytes==shape.source_pixel_bytes, + "invalid bounded grayscale footprint"); + } + shape.bounded=bounded_read_memory(row_width,row_height,unsigned(shape.selected_channels),unsigned(bytes), + number(bounded["retained_bytes"],decode_budget),shape.source_codec_bytes,shape.cms_buffer_bytes,workspace,sizes); + check(bounded_total(shape.bounded)<=decode_budget,"bounded decode footprint exceeds limit"); + } check(base.contains("deep")?(shape.deep_buffer_bytes==job.options.max_decode_mib*1024ULL*1024ULL && shape.selected_channels==4 && !categorical && !shape.source_buffer_bytes):shape.deep_buffer_bytes==0,"worker Deep budget mismatch"); check(shape.source_buffer_bytes?(job.options.visualization=="id" && base.contains("source_read") && base["source_read"]["buffer_bytes"]==shape.source_buffer_bytes):!base.contains("source_read"),"sampled source footprint mismatch"); check(shape.data_width && shape.data_height && shape.display_width && shape.display_height && shape.channel_span && (shape.selected_channels==3 || shape.selected_channels==4) && shape.output_width && shape.output_height && shape.source_sample_bytes && shape.source_pixel_bytes>=shape.source_sample_bytes && shape.source_pixel_bytes<=shape.source_sample_bytes*std::min(shape.channel_span,mode=="colour" || mode=="cryptomatte"?4:3) && - (mode!="colour" || (srgb8?shape.source_sample_bytes==1:integer_linear?(shape.source_sample_bytes==1 || shape.source_sample_bytes==2): + (mode!="colour" || bounded_gray || (srgb8?shape.source_sample_bytes==1:integer_linear?(shape.source_sample_bytes==1 || shape.source_sample_bytes==2): (shape.source_sample_bytes==4 && shape.source_pixel_bytes%4==0))),"invalid worker footprint"); std::uint64_t cost=1; try {auto estimate=estimate_memory(shape);estimate_mib=double(estimate.total)/1048576;task.admission_mib=double(estimate.incremental)/1048576;if(options.memory_mib)cost=estimate.incremental;} diff --git a/src/jpeg_rows.cpp b/src/jpeg_rows.cpp new file mode 100644 index 0000000..1022b43 --- /dev/null +++ b/src/jpeg_rows.cpp @@ -0,0 +1,207 @@ +#include "jpeg_rows.h" +#include "cms_input.h" +#include "files.h" +#include +#include +#include +#include +#include +#include +#include +#include + +namespace thumbgen::detail { +namespace { +constexpr std::uint64_t header_limit=8*bounded_mib; +constexpr std::uint64_t metadata_copies=8; +struct JpegError { + jpeg_error_mgr base{}; + std::jmp_buf jump; + char message[JMSG_LENGTH_MAX]{}; +}; +void jpeg_failed(j_common_ptr decoder) { + auto* error=reinterpret_cast(decoder->err); + decoder->err->format_message(decoder,error->message); + std::longjmp(error->jump,1); +} +void jpeg_warning(j_common_ptr decoder,int level) { + // An invalid ICC sequence is still visible to automatic colour selection. + // Its existing unsupported-profile error is distinct from a JPEG failure. + if(level<0 && decoder->err->msg_code!=JWRN_BOGUS_ICC)jpeg_failed(decoder); +} +using File=std::unique_ptr; +struct Decoder { + File file; + jpeg_decompress_struct jpeg{}; + JpegError error; + bool started=false; + explicit Decoder(File source):file(std::move(source)) { + jpeg.err=jpeg_std_error(&error.base); + error.base.error_exit=jpeg_failed; + error.base.emit_message=jpeg_warning; + } + ~Decoder(){jpeg_destroy_decompress(&jpeg);} + void header() { + if(setjmp(error.jump))throw FileFailure("open_failed",error.message); + jpeg_create_decompress(&jpeg); + jpeg_stdio_src(&jpeg,file.get()); + jpeg_save_markers(&jpeg,JPEG_APP0+1,0xffff); + jpeg_save_markers(&jpeg,JPEG_APP0+2,0xffff); + if(jpeg_read_header(&jpeg,TRUE)!=JPEG_HEADER_OK)throw FileFailure("open_failed","incomplete JPEG header"); + // APP segments between later scans must not accumulate during decode. + jpeg_save_markers(&jpeg,JPEG_APP0+1,0); + jpeg_save_markers(&jpeg,JPEG_APP0+2,0); + } +}; +// Limit the total header before asking libjpeg to retain any markers. This +// also prevents an arbitrary chain of empty segments from becoming unbounded. +std::uint64_t header_bytes(FILE* file) { + std::uint64_t bytes=2,marker_overhead=0; + auto byte=[&]() { + if(++bytes>header_limit)throw FileFailure("open_failed","JPEG header exceeds metadata limit"); + const int value=std::getc(file); + if(value==EOF)throw FileFailure("open_failed","truncated JPEG header"); + return value; + }; + for(;;) { + if(byte()!=0xff)throw FileFailure("open_failed","invalid JPEG header marker"); + int marker=byte(); + while(marker==0xff)marker=byte(); + if(marker==0 || marker==0xd8 || marker==0xd9 || (marker>=0xd0 && marker<=0xd7)) + throw FileFailure("open_failed","invalid JPEG header marker"); + if(marker==1)continue; + if((marker>=0xe0 && marker<=0xef) || marker==0xfe)marker_overhead+=128; + const auto high=byte(); + const int size=(high<<8)+byte()-2; + if(size<0 || (marker==0xda && size<6))throw FileFailure("open_failed","invalid JPEG segment length"); + if(std::uint64_t(size)+marker_overhead>header_limit-bytes)throw FileFailure("open_failed","JPEG header exceeds metadata limit"); + if(std::fseek(file,size,SEEK_CUR)!=0)throw FileFailure("open_failed","cannot read JPEG header"); + bytes+=size; + if(marker==0xda)return bytes+marker_overhead; + } +} +std::uint64_t ceil_div(std::uint64_t value,std::uint64_t unit){return value/unit+(value%unit!=0);} +std::uint64_t decoder_bytes(jpeg_decompress_struct& jpeg,std::uint64_t header) { + unsigned max_h=1,max_v=1; + for(int c=0;c4 || comp.v_samp_factor<1 || comp.v_samp_factor>4) + throw FileFailure("open_failed","invalid JPEG sampling factors"); + max_h=std::max(max_h,unsigned(comp.h_samp_factor)); + max_v=std::max(max_v,unsigned(comp.v_samp_factor)); + } + const auto columns=ceil_div(jpeg.image_width,8*max_h); + const auto rows=ceil_div(jpeg.image_height,8*max_v); + // Metadata copies plus a fixed allocator/table allowance and a + // width-scaled allowance for multiple iMCU row buffers and alignment. + auto bytes=checked_bytes_add(metadata_copies*header,4*bounded_mib+ + checked_bytes_mul(jpeg.image_width,8*max_v*jpeg.num_components*8)); + if(jpeg_has_multiple_scans(&jpeg)){ + for(int c=0;c decoder,std::uint64_t budget):decoder_(std::move(decoder)) { + auto& state=*decoder_; + auto& jpeg=state.jpeg; + if(state.started)throw FileFailure("decode_failed","JPEG decoder already started"); + state.started=true; + const int width=jpeg.image_width,height=jpeg.image_height,channels=jpeg.num_components; + if(setjmp(state.error.jump))throw FileFailure("decode_failed",state.error.message); + jpeg.mem->max_memory_to_use=static_cast(std::min(budget,std::numeric_limits::max())); + if(!jpeg_start_decompress(&jpeg) || jpeg.output_width!=unsigned(width) || + jpeg.output_height!=unsigned(height) || jpeg.output_components!=channels) + throw FileFailure("decode_failed","JPEG native layout changed during decode"); + stride_=std::size_t(width)*channels; + } + void read(int first,int last,void* destination) override { + auto& state=*decoder_; + auto& jpeg=state.jpeg; + if(first<0 || first>=last || unsigned(first)!=jpeg.output_scanline || unsigned(last)>jpeg.output_height) + throw FileFailure("decode_failed","JPEG rows must be read once in order"); + if(setjmp(state.error.jump))throw FileFailure("decode_failed",state.error.message); + auto* pixels=static_cast(destination); + while(jpeg.output_scanline decoder_; + std::size_t stride_=0; +}; +} + +std::optional probe_jpeg(const std::string& path,std::uint64_t budget,std::size_t icc_limit) { + File file(OIIO::Filesystem::fopen(path,"rb"),&std::fclose); + if(!file || std::getc(file.get())!=0xff || std::getc(file.get())!=0xd8)return std::nullopt; + const auto header=header_bytes(file.get()); + if(header>budget/metadata_copies)throw FileFailure("decode_limit_exceeded","JPEG metadata exceeds decode budget"); + std::rewind(file.get()); + auto decoder=std::make_shared(std::move(file)); + decoder->header(); + auto& jpeg=decoder->jpeg; + if(!jpeg.image_width || !jpeg.image_height || jpeg.image_width>JPEG_MAX_DIMENSION || jpeg.image_height>JPEG_MAX_DIMENSION || + jpeg.data_precision!=8 || (jpeg.num_components!=1 && jpeg.num_components!=3 && jpeg.num_components!=4)) + throw FileFailure("open_failed","unsupported JPEG dimensions or sample layout"); + JpegProbe result; + result.multiscan=jpeg_has_multiple_scans(&jpeg); + result.codec_bytes=decoder_bytes(jpeg,header); + if(result.codec_bytes>budget)throw FileFailure("decode_limit_exceeded","JPEG coefficients and decoder scratch exceed decode budget"); + const bool cmyk=jpeg.jpeg_color_space==JCS_CMYK || jpeg.jpeg_color_space==JCS_YCCK; + auto& spec=result.spec; + spec=OIIO::ImageSpec(jpeg.image_width,jpeg.image_height,cmyk?3:jpeg.num_components,OIIO::TypeDesc::UINT8); + spec.set_colorspace("srgb_rec709_scene"); + if(cmyk)spec.attribute("jpeg:ColorSpace",jpeg.jpeg_color_space==JCS_CMYK?"CMYK":"YCbCrK"); + if(jpeg.num_components>=3 && jpeg.comp_info[1].h_samp_factor==1 && jpeg.comp_info[1].v_samp_factor==1 && + jpeg.comp_info[2].h_samp_factor==1 && jpeg.comp_info[2].v_samp_factor==1) { + const auto h=jpeg.comp_info[0].h_samp_factor,v=jpeg.comp_info[0].v_samp_factor; + const char* sampling=h==1 && v==1?"4:4:4":h==2 && v==1?"4:2:2":h==2 && v==2?"4:2:0":h==4 && v==1?"4:1:1":nullptr; + if(sampling)spec.attribute("jpeg:subsampling",sampling); + } + std::size_t icc_bytes=0; + for(auto* marker=jpeg.marker_list;marker;marker=marker->next) { + const auto* p=marker->data; + const auto n=marker->data_length; + if(marker->marker==JPEG_APP0+1){ + constexpr char xmp[]="http://ns.adobe.com/xap/1.0/"; + if(n>=6 && !std::memcmp(p,"Exif\0",6))OIIO::decode_exif(OIIO::cspan(p+6,n-6),spec); + else if(n>=sizeof(xmp) && !std::memcmp(p,xmp,sizeof(xmp))) + OIIO::decode_xmp(OIIO::cspan(p,n),spec); + } + if(marker->marker==JPEG_APP0+2 && n>=12 && !std::memcmp(p,"ICC_PROFILE",12)){ + result.has_icc=true; + icc_bytes+=n>14?n-14:0; + } + } + if(icc_bytes>icc_limit)throw CmsFailure("JPEG ICC segments exceed profile limit"); + if(result.has_icc){ + JOCTET* profile=nullptr;unsigned size=0; + if(setjmp(decoder->error.jump))throw FileFailure("open_failed",decoder->error.message); + if(jpeg_read_icc_profile(&jpeg,&profile,&size)){ + const std::unique_ptr bytes(profile,&std::free); + spec.attribute("ICCProfile",OIIO::TypeDesc(OIIO::TypeDesc::UINT8,int(size)),bytes.get()); + } + } + if(jpeg.jpeg_color_space==JCS_GRAYSCALE || jpeg.jpeg_color_space==JCS_RGB || jpeg.jpeg_color_space==JCS_YCbCr) + result.read={unsigned(jpeg.num_components),0,result.codec_bytes, + [decoder,budget=result.codec_bytes]{return std::make_unique(decoder,budget);}}; + return result; +} +} diff --git a/src/jpeg_rows.h b/src/jpeg_rows.h new file mode 100644 index 0000000..3a3a4e3 --- /dev/null +++ b/src/jpeg_rows.h @@ -0,0 +1,20 @@ +#pragma once +#include "bounded_read.h" +#include +#include +#include + +namespace thumbgen::detail { +struct JpegProbe { + OIIO::ImageSpec spec; + NativeReadPlan read; + std::uint64_t codec_bytes=0; + bool has_icc=false; + bool multiscan=false; +}; +// SOI detection is independent of the filename. A recognized JPEG with an +// invalid header throws. The row factory owns the prepared decoder and leaves +// its first scan untouched until the controller admits the task. +std::optional probe_jpeg(const std::string& path,std::uint64_t budget, + std::size_t icc_limit=std::numeric_limits::max()); +} diff --git a/src/other_rows.cpp b/src/other_rows.cpp new file mode 100644 index 0000000..e639490 --- /dev/null +++ b/src/other_rows.cpp @@ -0,0 +1,121 @@ +#include "other_rows_internal.h" + +namespace thumbgen::detail::other_rows { +namespace { +OIIO::ImageInput::unique_ptr open(const std::string& path,const std::string& format, + const OIIO::ImageSpec& config,OIIO::ImageSpec& spec,const char* code) { + // Instantiate only the codec that was preflighted, including when the + // extension names another reader or when the plugin rejects the pixels. + auto input=OIIO::ImageInput::create(format); + if(!input)throw FileFailure(code,OIIO::geterror()); + if(!input->open(path,spec,config))throw FileFailure(code,input->geterror()); + return input; +} + +class PluginRows final : public NativeRowSource { +public: + PluginRows(const std::string& path,const std::string& format,const OIIO::ImageSpec& config, + const OIIO::ImageSpec& planned) { + OIIO::ImageSpec actual; + input_=open(path,format,config,actual,"decode_failed"); + if(actual.width!=planned.width || actual.height!=planned.height || actual.format!=planned.format || + actual.channelnames!=planned.channelnames || actual.x!=planned.x || actual.y!=planned.y || + actual.get_int_attribute("Orientation",1)!=planned.get_int_attribute("Orientation",1) || + actual.get_int_attribute("oiio:UnassociatedAlpha",0)!=planned.get_int_attribute("oiio:UnassociatedAlpha",0)) + throw FileFailure("decode_failed","native layout changed after admission"); + height_=actual.height; + y_=actual.y; + stride_=actual.scanline_bytes(); + } + void read(int first,int last,void* destination) override { + if(first!=next_ || first>=last || last>height_) + throw FileFailure("decode_failed","native rows must be read once in order"); + auto* out=static_cast(destination); + // Intentionally call the single-row API. Several native bulk-read + // implementations allocate a temporary sized by the whole request. + for(;next_read_native_scanline(0,0,y_+next_,0,out)) + throw FileFailure("decode_failed",input_->geterror()); + } + void finish() override { + if(next_!=height_ || !input_->close()) + throw FileFailure("decode_failed","incomplete native image decode"); + } +private: + OIIO::ImageInput::unique_ptr input_; + int next_=0,height_=0,y_=0; + std::size_t stride_=0; +}; +} + +OIIO::ImageSpec metadata(const Source& source,const char* format) { + OIIO::ImageSpec spec; + auto input=open(source.path,format,source.config,spec,"open_failed"); + return spec; +} + +OtherRowsProbe supported(const Source& source,const char* format,OIIO::ImageSpec spec, + std::uint64_t retained,std::uint64_t codec) { + const auto complete_codec=checked_bytes_add(codec,retained); + reserve(complete_codec,source.budget,"native frame and codec scratch exceed decode budget"); + // Capture only the layout. Avoid duplicating copied ICC and user metadata + // in the deferred factory or each adapter object. + OIIO::ImageSpec layout=spec; + layout.extra_attribs.clear(); + layout.attribute("Orientation",spec.get_int_attribute("Orientation",1)); + layout.attribute("oiio:UnassociatedAlpha",spec.get_int_attribute("oiio:UnassociatedAlpha",0)); + NativeReadPlan plan{unsigned(spec.pixel_bytes()),retained,codec, + [path=source.path,format=std::string(format),config=source.config,layout=std::move(layout)] { + return std::make_unique(path,format,config,layout); + }}; + return {format,std::move(spec),std::move(plan),complete_codec}; +} + +OtherRowsProbe fallback(const Source& source,const char* format,std::uint64_t pixels, + std::uint64_t codec,std::uint64_t eager) { + // An unusual layout must fit both the audited plugin workspace and the + // existing complete-image route. Eager allocations before scheduling + // must also fit the bounded metadata envelope. + reserve(eager,eager_limit,"unsupported layout requires a large decoder allocation before admission"); + reserve(checked_bytes_add(checked_bytes_mul(pixels,32),codec),source.budget, + "unsupported layout requires a complete image decode that exceeds decode budget"); + return {format,std::nullopt,{},codec}; +} +} + +namespace thumbgen::detail { +std::optional probe_other_rows(const std::string& path,std::uint64_t file_bytes, + std::uint64_t budget,const OIIO::ImageSpec& config,std::size_t icc_limit) { + using namespace other_rows; + Source source(path,file_bytes,budget,config); + if(!source.file)return std::nullopt; + std::array magic{}; + source.read(0,magic.data(),std::size_t(std::min(file_bytes,magic.size())),"truncated image signature"); + if(file_bytes>=12 && is(magic.data(),"RIFF") && is(magic.data()+8,"WEBP")) + return webp(source,icc_limit); + if(file_bytes>=4 && (is(magic.data(),"SDPX") || is(magic.data(),"XPDS")))return dpx(source); + if(file_bytes>=2 && (is(magic.data(),"BM",2) || is(magic.data(),"BA",2) || + is(magic.data(),"CI",2) || is(magic.data(),"CP",2) || is(magic.data(),"PT",2))) + return bmp(source); + if(file_bytes>=2 && is(magic.data(),"#?",2))return hdr(source); + // TGA 1.0 has no reliable signature. Use the known suffixes and the + // set of header layouts recognized by the plugin. + auto extension=std::filesystem::u8path(path).extension().u8string(); + for(auto& c:extension)if(c>='A' && c<='Z')c=char(c-'A'+'a'); + const bool tga_suffix=extension==".tga" || extension==".tpic"; + if(tga_suffix && file_bytes<18)return targa(source); + if(file_bytes>=18 && magic[1]<=1 && ((magic[2]>=1 && magic[2]<=3) || (magic[2]>=9 && magic[2]<=11))) { + std::array layout{}; + source.read(12,layout.data(),layout.size(),"truncated TGA layout"); + const auto bits=layout[4]; + if(tga_suffix || (le16(layout.data()) && le16(layout.data()+2) && + (bits==8 || bits==15 || bits==16 || bits==24 || bits==32)))return targa(source); + } + if(file_bytes>=26) { + std::array footer{}; + source.read(file_bytes-footer.size(),footer.data(),footer.size(),"truncated image footer"); + if(is(footer.data(),"TRUEVISION-XFILE.",18))return targa(source); + } + return std::nullopt; +} +} diff --git a/src/other_rows.h b/src/other_rows.h new file mode 100644 index 0000000..d9d497d --- /dev/null +++ b/src/other_rows.h @@ -0,0 +1,21 @@ +#pragma once +#include "bounded_read.h" +#include +#include +#include + +namespace thumbgen::detail { +struct OtherRowsProbe { + std::string format; + // With a spec, selection can proceed without an open decoder. With no + // spec, the existing OIIO metadata/selection path is preflighted for use. + std::optional spec; + NativeReadPlan read; + // Complete-image route only. Includes any native frame also retained + // by the bounded route and excludes the client's own decoded raster. + std::uint64_t fallback_codec_bytes=0; +}; + +std::optional probe_other_rows(const std::string& path,std::uint64_t file_bytes, + std::uint64_t budget,const OIIO::ImageSpec& config,std::size_t icc_limit); +} diff --git a/src/other_rows_internal.h b/src/other_rows_internal.h new file mode 100644 index 0000000..5fdf00a --- /dev/null +++ b/src/other_rows_internal.h @@ -0,0 +1,61 @@ +#pragma once +#include "other_rows.h" +#include "files.h" +#include +#include +#include + +namespace thumbgen::detail::other_rows { +inline constexpr std::uint64_t metadata_limit=4*bounded_mib; +inline constexpr std::uint64_t metadata_copies=16; +inline constexpr std::uint64_t eager_limit=8*bounded_mib; +inline constexpr std::uint64_t plugin_bytes=bounded_mib; + +using Byte=unsigned char; +inline bool is(const Byte* bytes,const char* literal,std::size_t size=4) { + return std::memcmp(bytes,literal,size)==0; +} +inline unsigned le16(const Byte* b){return unsigned(b[0])|(unsigned(b[1])<<8);} +inline std::uint32_t le24(const Byte* b){return le16(b)|(std::uint32_t(b[2])<<16);} +inline std::uint32_t le32(const Byte* b){return le24(b)|(std::uint32_t(b[3])<<24);} +inline void require(bool ok,const char* message) { + if(!ok)throw FileFailure("open_failed",message); +} +inline void reserve(std::uint64_t bytes,std::uint64_t budget,const char* message) { + if(bytes>budget)throw FileFailure("decode_limit_exceeded",message); +} +inline std::uint64_t dimensions(std::uint64_t w,std::uint64_t h,unsigned limit,const char* message) { + require(w && h,message); + reserve(std::max(w,h),limit,message); + return w*h; +} +struct Source { + const std::string& path; + std::uint64_t size,budget; + const OIIO::ImageSpec& config; + std::ifstream file; + Source(const std::string& name,std::uint64_t bytes,std::uint64_t limit,const OIIO::ImageSpec& options) + :path(name),size(bytes),budget(limit),config(options),file(std::filesystem::u8path(name),std::ios::binary){} + void read(std::uint64_t offset,void* out,std::size_t bytes,const char* message) { + require(offset<=size && bytes<=size-offset && offset<=std::uint64_t(std::numeric_limits::max()),message); + file.clear(); + file.seekg(static_cast(offset)); + require(bool(file.read(static_cast(out),static_cast(bytes))),message); + } + void extent(std::uint64_t offset,std::uint64_t bytes,const char* message) const { + require(offset<=size && bytes<=size-offset,message); + } +}; + +OIIO::ImageSpec metadata(const Source&,const char* format); +OtherRowsProbe supported(const Source&,const char* format,OIIO::ImageSpec, + std::uint64_t retained,std::uint64_t codec); +OtherRowsProbe fallback(const Source&,const char* format,std::uint64_t pixels, + std::uint64_t codec,std::uint64_t eager=0); + +OtherRowsProbe bmp(Source&); +OtherRowsProbe dpx(Source&); +OtherRowsProbe hdr(Source&); +OtherRowsProbe targa(Source&); +OtherRowsProbe webp(Source&,std::size_t icc_limit); +} diff --git a/src/png_rows.cpp b/src/png_rows.cpp new file mode 100644 index 0000000..9b89dd3 --- /dev/null +++ b/src/png_rows.cpp @@ -0,0 +1,165 @@ +#include "png_rows.h" +#include "files.h" +#include +#include +#include +#include +#include + +namespace thumbgen::detail { +namespace { +std::uint32_t be32(const unsigned char* p) { + return (std::uint32_t(p[0])<<24)|(std::uint32_t(p[1])<<16)|(std::uint32_t(p[2])<<8)|p[3]; +} + +struct PngHeader { + std::uint32_t width,height; + unsigned bits,type,interlace,channels; +}; + +std::optional png_header(const std::filesystem::path& path) { + std::array h{}; + const unsigned char prefix[]{137,80,78,71,13,10,26,10,0,0,0,13,'I','H','D','R'}; + std::ifstream file(path,std::ios::binary); + if(!file.read(reinterpret_cast(h.data()),h.size()) || + !std::equal(std::begin(prefix),std::end(prefix),h.begin()) || + h[26]!=0 || h[27]!=0 || h[28]>1 || crc32(0,h.data()+12,17)!=be32(h.data()+29))return {}; + + const auto width=be32(h.data()+16),height=be32(h.data()+20); + if(!width || !height || width>0x7fffffff || height>0x7fffffff)return {}; + const unsigned bits=h[24],type=h[25]; + const bool whole_sample=bits==8 || bits==16; + unsigned channels=0; + switch(type) { + case 0: if(whole_sample || bits==1 || bits==2 || bits==4)channels=1;break; + case 2: if(whole_sample)channels=3;break; + case 3: if(bits==1 || bits==2 || bits==4 || bits==8)channels=3;break; + case 4: if(whole_sample)channels=2;break; + case 6: if(whole_sample)channels=4;break; + } + if(!channels)return {}; + return PngHeader{width,height,bits,type,h[28],channels}; +} + +std::uint64_t frame_bytes(std::uint64_t row,std::uint64_t height,std::uint64_t budget) { + if(row>budget/height) + throw FileFailure("decode_limit_exceeded","Adam7 PNG native frame exceeds decode budget"); + return row*height; +} + +std::uint64_t metadata_bytes(const std::filesystem::path& path,bool include_tail,std::uint64_t budget) { + std::ifstream file(path,std::ios::binary); + file.seekg(33); + std::uint64_t bytes=0; + std::array h{}; + while(file.read(reinterpret_cast(h.data()),h.size())) { + const auto length=be32(h.data()); + const auto is=[&](const char* name) {return std::memcmp(h.data()+4,name,4)==0;}; + if(is("IEND"))break; + if(is("IDAT")) { + if(!include_tail)break; + } else { + bool deflated=is("iCCP") || is("zTXt"); + if(is("iTXt")) { + // The optional compression flag follows the NUL-terminated + // keyword, which PNG restricts to 79 bytes. + std::array prefix{}; + const auto count=std::min(length,prefix.size()); + const auto start=file.tellg(); + if(!file.read(reinterpret_cast(prefix.data()),std::streamsize(count)))break; + const auto end=prefix.begin()+count; + const auto nul=std::find(prefix.begin(),end,0); + deflated=end-nul>=2 && nul[1]!=0; + file.seekg(start); + } + // A DEFLATE length/distance pair consumes at least two bits and + // produces at most 258 bytes. Also cover retained raw metadata, + // transient inflate copies and copies in the image spec. + const auto payload=deflated?std::uint64_t(length)*1033:length; + bytes=checked_bytes_add(bytes,checked_bytes_mul(payload+128,8)); + if(bytes>budget)throw FileFailure("decode_limit_exceeded","PNG metadata exceeds decode budget"); + } + file.seekg(std::streamoff(length)+4,std::ios::cur); + } + return bytes; +} + +class PngRows final : public NativeRowSource { +public: + PngRows(OIIO::ImageInput& input,int y,int height,int z,std::size_t row_bytes) + :input_(input),y_(y),height_(height),z_(z),row_bytes_(row_bytes) {} + + void read(int first,int last,void* destination) override { + if(first!=next_ || last<=first || last>height_) + throw FileFailure("decode_failed","PNG rows must be read once in order"); + auto* output=static_cast(destination); + for(;next_width)*header->channels*(header->bits==16?2:1); + if(header->interlace)frame_bytes(row,header->height,budget); + const auto info=metadata_bytes(path,header->interlace!=0,budget); + if(checked_bytes_add(checked_bytes_mul(row,8),info)>budget) + throw FileFailure("decode_limit_exceeded","PNG header and rows exceed decode budget"); + return true; +} + +PngRowPlan plan_png_rows(const std::filesystem::path& path,OIIO::ImageInput& input, + const OIIO::ImageSpec& spec,std::uint64_t budget) { + const auto header=png_header(path); + if(!header || header->width!=std::uint64_t(spec.width) || header->height!=std::uint64_t(spec.height)) + throw FileFailure("open_failed","inconsistent PNG header"); + + const auto pixel=spec.pixel_bytes(true); + const auto row=checked_bytes_mul(header->width,pixel); + // libpng keeps filter/previous/expanded rows, its zlib state and header + // metadata. Include the libpng iCCP allocation even if CMS is bypassed. + auto codec=checked_bytes_add(checked_bytes_mul(row,8),512*1024); + codec=checked_bytes_add(codec,metadata_bytes(path,header->interlace!=0,budget)); + + std::uint64_t frame=0; + if(header->interlace) { + frame=frame_bytes(row,header->height,budget); + // OIIO's Adam7 read constructs one row pointer per scanline. + codec=checked_bytes_add(codec,checked_bytes_mul(header->height,sizeof(void*))); + } + PngRowPlan result; + result.fallback_codec_bytes=checked_bytes_add(codec,frame); + result.retains_frame=frame!=0; + if(result.fallback_codec_bytes>budget) + throw FileFailure("decode_limit_exceeded","PNG frame and decoder scratch exceed decode budget"); + + const unsigned bytes=header->bits==16?2:1; + const bool have_alpha=spec.nchannels==int(header->channels)+1 && + (header->type==0 || header->type==2) && spec.alpha_channel==spec.nchannels-1; + if(header->type==3 || (header->bits!=8 && header->bits!=16) || + spec.depth!=1 || spec.tile_width || !spec.channelformats.empty() || + (spec.nchannels!=int(header->channels) && !have_alpha) || + spec.format!=(bytes==2?OIIO::TypeDesc::UINT16:OIIO::TypeDesc::UINT8) || + header->width>65536 || header->height>65536 || + std::int64_t(spec.y)+spec.height-1>std::numeric_limits::max())return result; + + result.read={unsigned(pixel),frame,codec,[&input,y=spec.y,height=spec.height,z=spec.z,row] { + return std::make_unique(input,y,height,z,std::size_t(row)); + }}; + return result; +} +} diff --git a/src/png_rows.h b/src/png_rows.h new file mode 100644 index 0000000..44a2ca4 --- /dev/null +++ b/src/png_rows.h @@ -0,0 +1,20 @@ +#pragma once +#include "bounded_read.h" +#include +#include + +namespace thumbgen::detail { +struct PngRowPlan { + NativeReadPlan read; + std::uint64_t fallback_codec_bytes=0; + bool retains_frame=false; +}; + +// Before ImageInput::open, check the PNG header/metadata footprint and the +// minimum native frame size for Adam7. +bool preflight_png_header(const std::filesystem::path& path,std::uint64_t budget); + +// The metadata reader remains open through the row source's lifetime. +PngRowPlan plan_png_rows(const std::filesystem::path& path,OIIO::ImageInput& input, + const OIIO::ImageSpec& spec,std::uint64_t budget); +} diff --git a/src/selection.cpp b/src/selection.cpp index 883ea0f..7cc45db 100644 --- a/src/selection.cpp +++ b/src/selection.cpp @@ -92,6 +92,20 @@ bool is_primary(const OIIO::ImageSpec& spec,const Candidate& candidate) { }; return main_name(candidate.group) || (candidate.group=="RGB" && main_name(std::string(spec.get_string_attribute("oiio:subimagename")))); } +static bool unprefixed(const OIIO::ImageSpec& spec,const Candidate& candidate) { + return std::all_of(candidate.channels.begin(),candidate.channels.end(),[&](int c){ + return spec.channelnames[c].find('.')==std::string::npos; + }); +} +bool is_root_rgb(const OIIO::ImageSpec& spec,const Candidate& candidate) { + return candidate.kind=="colour" && candidate.group=="RGB" && unprefixed(spec,candidate); +} +bool is_auxiliary_aov(const OIIO::ImageSpec& spec,const Candidate& candidate) { + static const std::set names{"shadow","shadows","ao","ambientocclusion","ambient_occlusion","ambient occlusion","fresnel"}; + auto name=unprefixed(spec,candidate)?std::string(spec.get_string_attribute("oiio:subimagename")):candidate.group; + auto dot=name.rfind('.');if(dot!=std::string::npos)name=name.substr(dot+1); + return names.count(lower(name))!=0; +} Json selection_request(const Job& job) { const auto& o=job.options; Json request{{"part",o.part},{"part_name",o.part_name},{"channels",o.channels},{"strategy",o.selection_policy}}; diff --git a/src/selection.h b/src/selection.h index 1f54885..03e97b5 100644 --- a/src/selection.h +++ b/src/selection.h @@ -12,6 +12,8 @@ struct Candidate { std::vector classify(const OIIO::ImageSpec& spec); std::vector classify(const OIIO::ImageSpec& spec,const std::vector& crypto); bool is_primary(const OIIO::ImageSpec& spec, const Candidate& candidate); +bool is_root_rgb(const OIIO::ImageSpec& spec, const Candidate& candidate); +bool is_auxiliary_aov(const OIIO::ImageSpec& spec, const Candidate& candidate); Json candidate_json(const OIIO::ImageSpec& spec, const Candidate& candidate, int part); Candidate data_candidate(const OIIO::ImageSpec& spec,const Candidate& candidate,const std::string& requested,const DataMapping& mapping); } diff --git a/src/tga_rows.cpp b/src/tga_rows.cpp new file mode 100644 index 0000000..f7003b9 --- /dev/null +++ b/src/tga_rows.cpp @@ -0,0 +1,36 @@ +#include "other_rows_internal.h" + +namespace thumbgen::detail::other_rows { +OtherRowsProbe targa(Source& source) { + std::array header{}; + source.read(0,header.data(),header.size(),"truncated TGA header"); + const auto width=le16(header.data()+12),height=le16(header.data()+14); + const auto pixels=dimensions(width,height,65535,"invalid TGA dimensions"); + const auto type=header[2],bits=header[16],flags=header[17]; + if(header[1] || type!=2 || (bits!=24 && bits!=32) || (flags&0xc0)) { + // The plugin allocates one native frame of at most four channels and + // a palette of at most 65535 four-byte entries (included in the MiB). + return fallback(source,"targa",pixels,plugin_bytes+4*pixels); + } + const auto start=header.size()+header[0]; + const auto packed=pixels*(bits/8); + source.extent(start,packed,"truncated TGA image data"); + if(source.size>=26) { + std::array footer{}; + const auto end=source.size-footer.size(); + source.read(end,footer.data(),footer.size(),"truncated TGA footer"); + if(is(footer.data()+8,"TRUEVISION-XFILE.",17)) { + auto pixel_end=end; + for(auto offset:{le32(footer.data()),le32(footer.data()+4)}) { + if(!offset)continue; + require(offset<=end,"invalid TGA extension or developer offset"); + pixel_end=std::min(pixel_end,std::uint64_t(offset)); + } + require(start+packed<=pixel_end,"truncated TGA image data before metadata"); + } + } + reserve(plugin_bytes+packed,source.budget,"TGA native frame exceeds decode budget"); + auto spec=metadata(source,"targa"); + return supported(source,"targa",std::move(spec),packed,plugin_bytes); +} +} diff --git a/src/tiff_rows.cpp b/src/tiff_rows.cpp new file mode 100644 index 0000000..b0c39b7 --- /dev/null +++ b/src/tiff_rows.cpp @@ -0,0 +1,315 @@ +#include "tiff_rows.h" +#include "files.h" +#include +#include +#include + +namespace thumbgen::detail { +namespace { +using Tiff=std::unique_ptr; +using OpenOptions=std::unique_ptr; + +// The stock error printer would write to stderr in a worker. Record budget +// denials and leave malformed-directory reporting to the original reader. +int tiff_message(TIFF*,void* context,const char*,const char* format,va_list) { + if(context && format && std::strstr(format,"defined in open options")) + *static_cast(context)=true; + return 1; +} + +Tiff open_tiff(const std::filesystem::path& path,std::uint64_t budget,const char* mode,bool* denied=nullptr) { + OpenOptions options(TIFFOpenOptionsAlloc(),TIFFOpenOptionsFree); + if(!options)throw std::bad_alloc(); + const auto limit=std::min(budget,std::numeric_limits::max()); + TIFFOpenOptionsSetMaxSingleMemAlloc(options.get(),tmsize_t(limit)); + TIFFOpenOptionsSetMaxCumulatedMemAlloc(options.get(),tmsize_t(limit)); + TIFFOpenOptionsSetErrorHandlerExtR(options.get(),tiff_message,denied); + TIFFOpenOptionsSetWarningHandlerExtR(options.get(),tiff_message,denied); +#ifdef _WIN32 + return Tiff(TIFFOpenWExt(path.c_str(),mode,options.get()),TIFFClose); +#else + return Tiff(TIFFOpenExt(path.c_str(),mode,options.get()),TIFFClose); +#endif +} + +std::uint64_t bytes_mul(std::uint64_t a,std::uint64_t b) { + if(a && b>std::numeric_limits::max()/a) + throw FileFailure("decode_limit_exceeded","TIFF chunk size overflow"); + return a*b; +} + +std::uint64_t ceil_div(std::uint64_t value,std::uint64_t unit) { + return value/unit+(value%unit!=0); +} + +bool bounded_compression(unsigned compression) { + switch(compression) { + case COMPRESSION_NONE: case COMPRESSION_ADOBE_DEFLATE: case COMPRESSION_DEFLATE: + case COMPRESSION_LZW: case COMPRESSION_PACKBITS: return true; + default: return false; + } +} + +std::uint64_t spec_metadata_bytes(const OIIO::ImageSpec& spec) { + std::uint64_t bytes=0; + for(const auto& attr:spec.extra_attribs) { + bytes=checked_bytes_add(bytes,attr.name().size()+sizeof(OIIO::ParamValue)); + if(attr.datasize()>0)bytes=checked_bytes_add(bytes,std::uint64_t(attr.datasize())); + if(attr.type().basetype==OIIO::TypeDesc::STRING) + for(auto value:attr.as_cspan()) + bytes=checked_bytes_add(bytes,value.size()+1); + } + return bytes_mul(bytes,4); +} + +struct TiffLayout { + std::uint32_t width=0,height=0,depth=1,chunk_width=0,chunk_height=0,chunk_depth=1; + std::uint16_t channels=0,bits=0,format=0,photometric=0,planar=0,compression=0; + std::uint64_t chunk_bytes=0,across=0,slab_bytes=0,row_bytes=0; + std::uint32_t chunks=0; + bool tiled=false; +}; + +TiffLayout tiff_layout(TIFF* tif,const OIIO::ImageSpec& spec,std::uint64_t budget) { + TiffLayout layout; + TIFFGetField(tif,TIFFTAG_IMAGEWIDTH,&layout.width); + TIFFGetField(tif,TIFFTAG_IMAGELENGTH,&layout.height); + TIFFGetFieldDefaulted(tif,TIFFTAG_IMAGEDEPTH,&layout.depth); + TIFFGetFieldDefaulted(tif,TIFFTAG_SAMPLESPERPIXEL,&layout.channels); + TIFFGetFieldDefaulted(tif,TIFFTAG_BITSPERSAMPLE,&layout.bits); + TIFFGetFieldDefaulted(tif,TIFFTAG_SAMPLEFORMAT,&layout.format); + TIFFGetFieldDefaulted(tif,TIFFTAG_PHOTOMETRIC,&layout.photometric); + TIFFGetFieldDefaulted(tif,TIFFTAG_PLANARCONFIG,&layout.planar); + TIFFGetFieldDefaulted(tif,TIFFTAG_COMPRESSION,&layout.compression); + layout.tiled=TIFFIsTiled(tif)!=0; + if(layout.width!=std::uint64_t(spec.width) || layout.height!=std::uint64_t(spec.height) || + layout.tiled!=(spec.tile_width>0) || !layout.width || !layout.height || !layout.depth) + throw FileFailure("decode_failed","TIFF directory differs from selected layout"); + if(layout.tiled) { + TIFFGetField(tif,TIFFTAG_TILEWIDTH,&layout.chunk_width); + TIFFGetField(tif,TIFFTAG_TILELENGTH,&layout.chunk_height); + TIFFGetFieldDefaulted(tif,TIFFTAG_TILEDEPTH,&layout.chunk_depth); + } else { + layout.chunk_width=layout.width; + TIFFGetFieldDefaulted(tif,TIFFTAG_ROWSPERSTRIP,&layout.chunk_height); + // UINT32_MAX is the defined default: one strip for the image. + layout.chunk_height=std::min(layout.chunk_height,layout.height); + } + if(!layout.chunk_width || !layout.chunk_height || !layout.chunk_depth || + !layout.channels || !layout.bits) + throw FileFailure("decode_failed","invalid TIFF chunk geometry"); + + const auto pixels=bytes_mul(bytes_mul(layout.chunk_width,layout.chunk_height),layout.chunk_depth); + const auto container_bytes=ceil_div(bytes_mul(pixels,layout.bits),8); + // Even a single sample plane must fit; check independently of libtiff's + // size return so a wrapped size cannot be used to admit a huge tile. + if(container_bytes>budget || container_bytes>std::uint64_t(std::numeric_limits::max())) + throw FileFailure("decode_limit_exceeded","TIFF strip or tile exceeds decode budget"); + + layout.chunk_bytes=layout.tiled?TIFFTileSize64(tif):TIFFStripSize64(tif); + layout.across=ceil_div(layout.width,layout.chunk_width); + const auto planes=layout.planar==PLANARCONFIG_SEPARATE?layout.channels:1; + const auto count=bytes_mul(bytes_mul(layout.across,ceil_div(layout.height,layout.chunk_height)), + bytes_mul(ceil_div(layout.depth,layout.chunk_depth),planes)); + layout.chunks=layout.tiled?TIFFNumberOfTiles(tif):TIFFNumberOfStrips(tif); + if(!layout.chunk_bytes || count!=layout.chunks) + throw FileFailure("decode_failed","inconsistent TIFF strip or tile layout"); + if(layout.chunk_bytes>budget || layout.chunk_bytes>std::uint64_t(std::numeric_limits::max()) || + count>budget/32) + throw FileFailure("decode_limit_exceeded","TIFF chunk or offset table exceeds decode budget"); + layout.row_bytes=bytes_mul(layout.width,spec.pixel_bytes(true)); + layout.slab_bytes=bytes_mul(layout.row_bytes,std::min(layout.height,layout.chunk_height)); + return layout; +} + +struct StrileBytes { + std::uint64_t largest=0; + bool sparse=false; +}; + +StrileBytes strile_bytes(TIFF* tif,std::uint32_t chunks,std::uint64_t size) { + StrileBytes result; + for(std::uint32_t i=0;isize || count>size-offset) + throw FileFailure("decode_failed","invalid TIFF strip or tile extent"); + result.sparse|=!offset || !count; + result.largest=std::max(result.largest,count); + } + return result; +} + +bool matching_samples(const TiffLayout& l,const OIIO::ImageSpec& spec,TIFF* tif) { + const int colours=l.photometric==PHOTOMETRIC_RGB?3:1; + if(l.photometric!=PHOTOMETRIC_RGB && l.photometric!=PHOTOMETRIC_MINISBLACK && + l.photometric!=PHOTOMETRIC_MINISWHITE)return false; + if(l.channels!=spec.nchannels || l.channelscolours+1)return false; + // MINISWHITE plus alpha is ambiguous in the OIIO paths, which can + // invert every component. Keep the original read path for that pairing. + if(l.photometric==PHOTOMETRIC_MINISWHITE && l.channels!=1)return false; + if(l.channels==colours)return spec.alpha_channel<0; + std::uint16_t count=0; + std::uint16_t* extra=nullptr; + if(!TIFFGetField(tif,TIFFTAG_EXTRASAMPLES,&count,&extra) || count!=1 || !extra || + spec.alpha_channel!=colours)return false; + return spec.get_int_attribute("oiio:UnassociatedAlpha",0)?*extra==EXTRASAMPLE_UNASSALPHA: + *extra==EXTRASAMPLE_ASSOCALPHA; +} + +class TiffRows final : public NativeRowSource { +public: + TiffRows(Tiff tif,TiffLayout layout) + :tif_(std::move(tif)),layout_(layout),slab_(std::size_t(layout.slab_bytes)), + tile_(layout.tiled?std::size_t(layout.chunk_bytes):0) {} + + void read(int first,int last,void* destination) override { + if(first<0 || std::uint32_t(first)!=next_ || last<=first || std::uint32_t(last)>layout_.height) + throw FileFailure("decode_failed","TIFF rows must be read once in order"); + auto* output=static_cast(destination); + while(next_(layout_.width-x,layout_.chunk_width)*pixel_bytes; + for(std::uint32_t y=0;y slab_,tile_; + std::uint32_t next_=0,group_begin_=0,group_end_=0; +}; +} + +bool preflight_tiff_header(const std::filesystem::path& path,std::uint64_t budget) { + std::ifstream file(path,std::ios::binary); + unsigned char h[4]{}; + if(!file.read(reinterpret_cast(h),sizeof(h)))return false; + const bool little=h[0]=='I' && h[1]=='I' && (h[2]==42 || h[2]==43) && h[3]==0; + const bool big=h[0]=='M' && h[1]=='M' && h[2]==0 && (h[3]==42 || h[3]==43); + if(!little && !big)return false; + file.close(); + + bool denied=false; + // Mirror the OIIO reader's eager table loading, default strip chopping, + // EXIF/GPS loads and directory traversal, without reading any pixels. + auto input=open_tiff(path,budget,"rm",&denied); + if(input) { + do { + const auto page=TIFFCurrentDirectory(input.get()); + for(const auto tag:{TIFFTAG_EXIFIFD,TIFFTAG_GPSIFD}) { + toff_t offset=0; + if(TIFFGetField(input.get(),tag,&offset)) { + TIFFReadEXIFDirectory(input.get(),offset); + if(denied || !TIFFSetDirectory(input.get(),page))break; + } + } + } while(!denied && !TIFFLastDirectory(input.get()) && TIFFReadDirectory(input.get())); + } + if(denied)throw FileFailure("decode_limit_exceeded","TIFF directory metadata exceeds decode budget"); + return true; +} + +TiffRowPlan plan_tiff_rows(const std::filesystem::path& path,const OIIO::ImageSpec& spec, + int part,std::uint64_t budget) { + // Prevent mmap and use on-disk strip geometry for the native reader. + auto tif=open_tiff(path,budget,"rmch"); + if(!tif || part<0 || !TIFFSetDirectory(tif.get(),tdir_t(part))) + throw FileFailure("decode_failed","could not inspect selected TIFF directory within decode budget"); + + const auto layout=tiff_layout(tif.get(),spec,budget); + const auto extents=strile_bytes(tif.get(),layout.chunks,std::filesystem::file_size(path)); + if(extents.largest>budget) + throw FileFailure("decode_limit_exceeded","compressed TIFF strip or tile exceeds decode budget"); + const auto raw=checked_bytes_add(bytes_mul(extents.largest,2),64*1024); + const auto tables=bytes_mul(layout.chunks,32); + // The native codecs are serial. Cover the compressed buffer, replacement + // during growth, directory arrays, libtiff state and inflate/LZW tables. + const bool known_codec=bounded_compression(layout.compression); + const auto metadata=checked_bytes_add(tables,spec_metadata_bytes(spec)); + const auto codec=checked_bytes_add(checked_bytes_add(raw,metadata),known_codec?512*1024:8*bounded_mib); + const auto group=layout.tiled?bytes_mul(layout.chunk_bytes,layout.across):layout.slab_bytes; + if(codec>budget)throw FileFailure("decode_limit_exceeded","TIFF decoder scratch exceeds decode budget"); + + TiffRowPlan result; + // The complete OIIO reader can retain several native/padded tile copies, + // or batches of separate planes/raw ZIP strips. Include that working + // storage and the optional whole-image RGBA conversion for legacy codecs. + const auto native_full=bytes_mul(layout.row_bytes,layout.height); + const auto chunk_guard=layout.tiled?bytes_mul(std::max(group, + bytes_mul(bytes_mul(bytes_mul(layout.chunk_width,layout.chunk_height),layout.chunk_depth), + std::max(spec.pixel_bytes(true),4ULL*spec.nchannels))),4): + checked_bytes_add(bytes_mul(layout.slab_bytes,4),bytes_mul(std::min(native_full,64*bounded_mib),2)); + const auto photo=layout.photometric; + const bool rgba_interface=photo==PHOTOMETRIC_YCBCR || photo==PHOTOMETRIC_CIELAB || + photo==PHOTOMETRIC_ICCLAB || photo==PHOTOMETRIC_ITULAB || + photo==PHOTOMETRIC_LOGL || photo==PHOTOMETRIC_LOGLUV || + ((layout.compression==COMPRESSION_JPEG || layout.compression==COMPRESSION_OJPEG) && spec.nchannels!=3); + const auto legacy=rgba_interface?bytes_mul(bytes_mul(layout.width,layout.height),4):0; + result.fallback_codec_bytes=checked_bytes_add(checked_bytes_add(codec,chunk_guard),legacy); + + if(!known_codec || layout.planar!=PLANARCONFIG_CONTIG || layout.format!=SAMPLEFORMAT_UINT || + (layout.bits!=8 && layout.bits!=16) || layout.depth!=1 || layout.chunk_depth!=1 || + layout.width>65536 || layout.height>65536 || spec.depth!=1 || !spec.channelformats.empty() || + spec.format!=(layout.bits==16?OIIO::TypeDesc::UINT16:OIIO::TypeDesc::UINT8) || + extents.sparse || !matching_samples(layout,spec,tif.get()))return result; + + const auto pixel=unsigned(layout.channels*(layout.bits/8)); + const auto packed_chunk=bytes_mul(bytes_mul(layout.chunk_width,layout.chunk_height),pixel); + if(layout.chunk_bytes!=packed_chunk || layout.row_bytes!=std::uint64_t(layout.width)*pixel) + throw FileFailure("decode_failed","TIFF native chunk byte size differs from selected layout"); + const auto retained=checked_bytes_add(layout.slab_bytes,layout.tiled?layout.chunk_bytes:0); + if(checked_bytes_add(retained,codec)>budget) + throw FileFailure("decode_limit_exceeded","TIFF native strip or tile group exceeds decode budget"); + + result.read={pixel,retained,codec,[path,part,layout,codec] { + // Apply the admitted codec reservation to the decode handle itself. + // Reserve part of it for zlib/libdeflate allocations outside libtiff. + auto decoder=open_tiff(path,codec-256*1024,"rmch"); + if(!decoder || !TIFFSetDirectory(decoder.get(),tdir_t(part))) + throw FileFailure("decode_failed","could not open admitted TIFF directory"); + return std::make_unique(std::move(decoder),layout); + }}; + return result; +} +} diff --git a/src/tiff_rows.h b/src/tiff_rows.h new file mode 100644 index 0000000..aa189ef --- /dev/null +++ b/src/tiff_rows.h @@ -0,0 +1,18 @@ +#pragma once +#include "bounded_read.h" +#include +#include + +namespace thumbgen::detail { +struct TiffRowPlan { + NativeReadPlan read; + std::uint64_t fallback_codec_bytes=0; +}; + +// Check the directories OIIO will inspect using the locked libtiff allocator +// limits before opening OIIO's metadata reader. +bool preflight_tiff_header(const std::filesystem::path& path,std::uint64_t budget); + +TiffRowPlan plan_tiff_rows(const std::filesystem::path& path,const OIIO::ImageSpec& spec, + int part,std::uint64_t budget); +} diff --git a/src/webp_rows.cpp b/src/webp_rows.cpp new file mode 100644 index 0000000..1c656c3 --- /dev/null +++ b/src/webp_rows.cpp @@ -0,0 +1,143 @@ +#include "other_rows_internal.h" +#include "cms_input.h" +#include + +namespace thumbgen::detail::other_rows { +namespace { +constexpr std::uint64_t chunk_limit=65536; +struct Chunk { + std::uint64_t offset=0; + std::uint32_t size=0; +}; +void record(Chunk& chunk,std::uint64_t offset,std::uint32_t size) { + require(chunk.offset==0,"duplicate WebP chunk"); + chunk={offset,size}; +} + +std::uint64_t lossless_scratch(std::uint64_t width,std::uint64_t height) { + // VP8L maintains an ARGB decode cache and subsampled transform maps. + // Entropy groups are indexed on a grid with tiles of at least 4x4; + // account for group mapping and Huffman tables even for small images. + const auto groups=std::min(65536,((width+3)/4)*((height+3)/4)); + return 8*width*height+65536*groups; +} +} + +OtherRowsProbe webp(Source& source,std::size_t icc_limit) { + // OIIO allocates the entire physical file, including trailing bytes. + reserve(source.size,source.budget,"WebP compressed source exceeds decode budget"); + std::array header{}; + source.read(4,header.data(),4,"truncated WebP container"); + const auto end=8+std::uint64_t(le32(header.data())); + source.extent(0,end,"truncated WebP container"); + Chunk extended,vp8,vp8l,alpha,icc,exif,animation; + std::uint64_t count=0,metadata_bytes=0; + unsigned flags=0,width=0,height=0; + bool frames=false; + for(std::uint64_t position=12;position=8,"truncated WebP chunk header"); + source.read(position,header.data(),8,"truncated WebP chunk header"); + const auto size=le32(header.data()+4); + const auto payload=position+8,padded=std::uint64_t(size)+(size&1); + require(padded<=end-payload,"truncated WebP chunk payload"); + if(is(header.data(),"VP8X")) { + require(position==12 && size==10,"invalid WebP extended header"); + record(extended,payload,size); + source.read(payload,header.data(),10,"truncated WebP extended header"); + flags=header[0]; + require(!(flags&~0x3e) && !le24(header.data()+1),"invalid WebP extended flags"); + width=le24(header.data()+4)+1; + height=le24(header.data()+7)+1; + dimensions(width,height,16383,"WebP canvas dimensions exceed supported limits"); + } else if(is(header.data(),"VP8 "))record(vp8,payload,size); + else if(is(header.data(),"VP8L"))record(vp8l,payload,size); + else if(is(header.data(),"ALPH"))record(alpha,payload,size); + else if(is(header.data(),"ICCP")) { + if(size>icc_limit)throw CmsFailure("WebP ICC chunk exceeds profile limit"); + record(icc,payload,size); + metadata_bytes+=size; + } else if(is(header.data(),"EXIF")) { + record(exif,payload,size); + metadata_bytes+=size; + } else if(is(header.data(),"ANIM"))record(animation,payload,size); + else if(is(header.data(),"ANMF"))frames=true; + position=payload+padded; + } + const bool animated=(flags&2)!=0; + require(animated==(animation.offset!=0) && animated==frames,"invalid WebP animation layout"); + require(animated?(!vp8.offset && !vp8l.offset):(bool(vp8.offset)!=bool(vp8l.offset)), + "invalid WebP image chunk layout"); + bool lossy_alpha=false; + if(!animated) { + unsigned image_width=0,image_height=0; + if(vp8.offset) { + require(vp8.size>=10,"truncated WebP VP8 header"); + source.read(vp8.offset,header.data(),10,"truncated WebP VP8 header"); + require(!(header[0]&1) && header[3]==0x9d && header[4]==1 && header[5]==0x2a, + "invalid WebP VP8 key frame"); + image_width=le16(header.data()+6)&0x3fff; + image_height=le16(header.data()+8)&0x3fff; + } else { + require(vp8l.size>=5,"truncated WebP lossless header"); + source.read(vp8l.offset,header.data(),5,"truncated WebP lossless header"); + const auto layout=le32(header.data()+1); + require(header[0]==0x2f && !(layout>>29),"invalid WebP lossless header"); + image_width=(layout&0x3fff)+1; + image_height=((layout>>14)&0x3fff)+1; + if(!extended.offset && ((layout>>28)&1))flags|=0x10; + } + require(!extended.offset || (width==image_width && height==image_height), + "WebP canvas and frame dimensions do not match"); + width=image_width; + height=image_height; + if(alpha.offset) { + require(vp8.offset && alpha.size && extended.offset && (flags&0x10),"invalid WebP alpha chunk"); + source.read(alpha.offset,header.data(),1,"truncated WebP alpha header"); + const auto method=header[0]&3; + require(method<=1 && !(header[0]&0xc0),"invalid WebP alpha encoding"); + if(method==0)require(alpha.size>std::uint64_t(width)*height,"truncated raw WebP alpha"); + lossy_alpha=method==1; // VP8L-compressed alpha in an otherwise VP8 image. + } + } + require(!vp8.offset || bool(flags&0x10)==bool(alpha.offset),"missing WebP alpha data"); + const auto pixels=dimensions(width,height,16383,"WebP canvas dimensions exceed supported limits"); + const bool has_alpha=(flags&0x10)!=0; + const auto retained=pixels*(has_alpha?4:3); + reserve(metadata_bytes,metadata_limit,"WebP metadata exceeds limit"); + // The lossy decoder uses macroblock-row caches with no internal RGB + // output (DecodeRGB[A]Into). Alpha has up to two native byte planes. + // Reserve demux nodes separately from payload and copied metadata. + const auto eager=source.size+retained+metadata_bytes*metadata_copies+count*256; + const auto codec=eager-retained+plugin_bytes+512*std::uint64_t(width)+ + (has_alpha?2*pixels:0)+(lossy_alpha?lossless_scratch(width,height):0); + reserve(retained+codec,source.budget,"WebP source, native frame and codec scratch exceed decode budget"); + if(animated || vp8l.offset) { + const auto scratch=lossless_scratch(width,height)+(animated?4*pixels:0); + return fallback(source,"webp",pixels,retained+codec+scratch,eager); + } + + OIIO::ImageSpec spec(int(width),int(height),has_alpha?4:3,OIIO::TypeDesc::UINT8); + spec.set_colorspace("srgb_rec709_scene"); + if(has_alpha && source.config.get_int_attribute("oiio:UnassociatedAlpha",0)) + spec.attribute("oiio:UnassociatedAlpha",1); + if((flags&8) && exif.size) { + std::vector bytes(exif.size); + source.read(exif.offset,bytes.data(),bytes.size(),"truncated WebP EXIF"); + const auto prefix=bytes.size()>=6 && is(bytes.data(),"Exif\0\0",6)?6:0; + if(bytes.size()>=std::size_t(prefix)+8 && + !OIIO::decode_exif(bytes,spec) && OIIO::get_int_attribute("imageinput:strict")) + throw FileFailure("open_failed","could not decode WebP EXIF"); + } + if((flags&0x20) && icc.offset) { + std::vector bytes(icc.size); + if(!bytes.empty())source.read(icc.offset,bytes.data(),bytes.size(),"truncated WebP ICC profile"); + if(!bytes.empty()) + spec.attribute("ICCProfile",OIIO::TypeDesc(OIIO::TypeDesc::UINT8,int(bytes.size())),bytes.data()); + std::string error; + if(!OIIO::decode_icc_profile(bytes,spec,error) && OIIO::get_int_attribute("imageinput:strict")) + throw FileFailure("open_failed","could not decode WebP ICC profile: "+error); + } + return supported(source,"webp",std::move(spec),retained,codec); +} +} diff --git a/tests/ci/test_audits.py b/tests/ci/test_audits.py index 4b2f367..f2ba916 100644 --- a/tests/ci/test_audits.py +++ b/tests/ci/test_audits.py @@ -97,7 +97,7 @@ def test_release_scope_and_python_contamination(self): reply.mkdir(parents=True) expected = {'thumbgen': 'EXECUTABLE', 'thumbgen_core': 'STATIC_LIBRARY', 'thumbgen_runtime': 'STATIC_LIBRARY', 'thumbgen_schedule': 'STATIC_LIBRARY', - 'thumbgen_skcms': 'STATIC_LIBRARY'} + 'thumbgen_skcms': 'STATIC_LIBRARY', 'thumbgen_c2': 'STATIC_LIBRARY'} targets = [] for name, kind in expected.items(): (reply / (name + '.json')).write_text(json.dumps(dict(name=name, type=kind))) @@ -111,11 +111,12 @@ def test_release_scope_and_python_contamination(self): with self.assertRaisesRegex(RuntimeError, 'scope'): ci.audit_release(directory) (reply / 'model.json').write_text(json.dumps(dict(configurations=[dict(targets=targets)]))) - (reply / 'thumbgen_skcms.json').write_text(json.dumps(dict(name='thumbgen_skcms', type='SHARED_LIBRARY'))) + c2_target = reply / 'thumbgen_c2.json' + c2_target.write_text(json.dumps(dict(name='thumbgen_c2', type='SHARED_LIBRARY'))) with self.assertRaisesRegex(RuntimeError, 'scope'): ci.audit_release(directory) - (reply / 'thumbgen_skcms.json').write_text(json.dumps(dict(name='thumbgen_skcms', type='STATIC_LIBRARY'))) - (reply / 'model.json').write_text(json.dumps(dict(configurations=[dict(targets=targets + targets[:1])]))) + c2_target.write_text(json.dumps(dict(name='thumbgen_c2', type='STATIC_LIBRARY'))) + (reply / 'model.json').write_text(json.dumps(dict(configurations=[dict(targets=targets + targets[-1:])]))) with self.assertRaisesRegex(RuntimeError, 'scope'): ci.audit_release(directory) (reply / 'model.json').write_text(json.dumps(dict(configurations=[dict(targets=targets)]))) diff --git a/tests/color_input_probe.cpp b/tests/color_input_probe.cpp index bc6bec3..595cd4e 100644 --- a/tests/color_input_probe.cpp +++ b/tests/color_input_probe.cpp @@ -13,6 +13,13 @@ static int emit(const nlohmann::json& result) { } int main(int argc,char** argv) { if(argc<2)return 2; + if(argc==3 && std::string(argv[1])=="--write-exr") { + auto out=OIIO::ImageOutput::create(argv[2]);if(!out)return 1; + OIIO::ImageSpec spec(8,8,3,OIIO::TypeDesc::FLOAT); + std::vector values(spec.image_pixels()*spec.nchannels,0.25f); + if(!out->open(argv[2],spec) || !out->write_image(OIIO::TypeDesc::FLOAT,values.data()) || !out->close())return 1; + return emit({{"written",true}}); + } if(argc==3 && std::string(argv[1])=="--write-webp") { auto out=OIIO::ImageOutput::create(argv[2]);if(!out)return 1; OIIO::ImageSpec spec(8,8,4,OIIO::TypeDesc::UINT8);spec.attribute("compression","lossless"); diff --git a/tests/output_fault.cmake b/tests/output_fault.cmake index 4fb29ee..cadb0c7 100644 --- a/tests/output_fault.cmake +++ b/tests/output_fault.cmake @@ -8,16 +8,14 @@ foreach(property IN ITEMS COMPILE_DEFINITIONS COMPILE_OPTIONS INCLUDE_DIRECTORIE endif() endforeach() get_target_property(fault_links thumbgen_core LINK_LIBRARIES) -if(THUMBGEN_C2_PNG_STREAM) - add_library(thumbgen_output_fault_c2 STATIC src/c2_resize.cpp) - target_compile_features(thumbgen_output_fault_c2 PRIVATE cxx_std_20) - get_target_property(c2_options thumbgen_c2 COMPILE_OPTIONS) - target_compile_options(thumbgen_output_fault_c2 PRIVATE ${c2_options}) - target_compile_definitions(thumbgen_output_fault_c2 PRIVATE THUMBGEN_OUTPUT_FAULT_TESTS=1) - target_link_libraries(thumbgen_output_fault_c2 PRIVATE OpenImageIO::OpenImageIO) - list(REMOVE_ITEM fault_links thumbgen_c2) - list(APPEND fault_links thumbgen_output_fault_c2) -endif() +add_library(thumbgen_output_fault_c2 STATIC src/c2_resize.cpp) +target_compile_features(thumbgen_output_fault_c2 PRIVATE cxx_std_20) +get_target_property(c2_options thumbgen_c2 COMPILE_OPTIONS) +target_compile_options(thumbgen_output_fault_c2 PRIVATE ${c2_options}) +target_compile_definitions(thumbgen_output_fault_c2 PRIVATE THUMBGEN_OUTPUT_FAULT_TESTS=1) +target_link_libraries(thumbgen_output_fault_c2 PRIVATE OpenImageIO::OpenImageIO) +list(REMOVE_ITEM fault_links thumbgen_c2) +list(APPEND fault_links thumbgen_output_fault_c2) target_link_libraries(thumbgen_output_fault_core PRIVATE ${fault_links}) target_compile_features(thumbgen_output_fault_core PUBLIC cxx_std_17) target_compile_definitions(thumbgen_output_fault_core PRIVATE THUMBGEN_OUTPUT_FAULT_TESTS=1) diff --git a/tests/test_aov.cpp b/tests/test_aov.cpp index 633f903..ebabef6 100644 --- a/tests/test_aov.cpp +++ b/tests/test_aov.cpp @@ -17,6 +17,41 @@ template static void write(const fs::path& path,OIIO::ImageSpec spec,OI require(output->open(path.u8string(),spec),output->geterror()); require(output->write_image(type,pixels.data()),output->geterror());require(output->close(),output->geterror()); } +static OIIO::ImageSpec colour_part(const char* name,std::vector channels) { + OIIO::ImageSpec spec(4,2,int(channels.size()),OIIO::TypeDesc::FLOAT); + spec.channelnames=std::move(channels); + spec.attribute("oiio:subimagename",name); + return spec; +} +static void selection_fixtures(const fs::path& root,Json& files) { + const auto rgb=colour_part("main",{"R","G","B","A","Z","AO.R","AO.G","AO.B", + "diffuse_indirect.R","diffuse_indirect.G","diffuse_indirect.B"}); + const auto shadow=colour_part("sHaDoW",{"R","G","B"}); + const auto passes=colour_part("passes",{"Fresnel.R","Fresnel.G","Fresnel.B","Normal.R","Normal.G","Normal.B"}); + const auto alternate=colour_part("alternate",{"R","G","B"}); + const auto beauty=colour_part("Beauty",{"R","G","B"}); + auto save=[&](const char* name,std::vector parts) { + auto path=(root/name).u8string(); + auto output=OIIO::ImageOutput::create(path);require(bool(output),OIIO::geterror()); + require(output->open(path,int(parts.size()),parts.data()),output->geterror()); + for(std::size_t part=0;partopen(path,parts[part],OIIO::ImageOutput::AppendSubimage),output->geterror()); + std::vector pixels(8*parts[part].nchannels,.5f); + require(output->write_image(OIIO::TypeDesc::FLOAT,pixels.data()),output->geterror()); + } + require(output->close(),output->geterror()); + files[name]=path; + }; + save("main-first.exr",{rgb,shadow,passes}); + save("main-last.exr",{passes,shadow,rgb}); + save("named-primary.exr",{rgb,shadow,beauty}); + save("two-roots.exr",{rgb,alternate,shadow}); + save("root-with-light-groups.exr",{colour_part("main",{"R","G","B","diffuse_direct.R","diffuse_direct.G","diffuse_direct.B"})}); + save("root-with-primary.exr",{colour_part("main",{"R","G","B","Beauty.R","Beauty.G","Beauty.B"})}); + save("other-view.exr",{rgb,colour_part("views",{"ShadowCamera.R","ShadowCamera.G","ShadowCamera.B"})}); + save("two-views.exr",{colour_part("views",{"left.R","left.G","left.B","right.R","right.G","right.B"})}); + save("prefixed-rgb.exr",{colour_part("main",{"RGB.R","RGB.G","RGB.B"}),shadow}); +} static Json fixtures(const fs::path& root) { require(fs::create_directory(root),"fixture directory exists"); OIIO::ImageSpec depth(4,2,1,OIIO::TypeDesc::FLOAT);depth.channelnames={"Z"}; @@ -55,7 +90,9 @@ static Json fixtures(const fs::path& root) { write(root/"labels.exr",labels,OIIO::TypeDesc::FLOAT,std::vector{1,0,0,0,1,0,0,0,1,.5f,.25f,.75f,1,0,0,0,1,0,0,0,1,.5f,.25f,.75f}); labels.set_format(OIIO::TypeDesc::UINT8);labels.channelnames={"R","G","B"}; write(root/"labels.png",labels,OIIO::TypeDesc::UINT8,std::vector{255,0,0,0,255,0,0,0,255,128,64,191,255,0,0,0,255,0,0,0,255,128,64,191}); - Json result;for(const char* name:{"depth.exr","depthgood.exr","depth16.tif","normal.exr","vector.exr","ids.exr","idsdouble.tif","idsfloat.exr","crypto.exr","window.exr","idwindow.exr","oriented.tif","labels.exr","labels.png"})result[name]=(root/name).u8string();return result; + Json result;for(const char* name:{"depth.exr","depthgood.exr","depth16.tif","normal.exr","vector.exr","ids.exr","idsdouble.tif","idsfloat.exr","crypto.exr","window.exr","idwindow.exr","oriented.tif","labels.exr","labels.png"})result[name]=(root/name).u8string(); + selection_fixtures(root,result); + return result; } static std::vector read(const fs::path& path,int width,int height) { auto input=OIIO::ImageInput::open(path.u8string());require(bool(input),OIIO::geterror()); diff --git a/tests/test_aov_cli.py b/tests/test_aov_cli.py index 8d4e216..0f9c6b9 100644 --- a/tests/test_aov_cli.py +++ b/tests/test_aov_cli.py @@ -123,6 +123,59 @@ def test_invalid_error_publishes_nothing(self): def test_crypto_metadata_refused(self): self.assertEqual(self.convert('crypto.exr','id','Object00.R',exit=4)[0]['error']['code'],'cryptomatte_requires_visualization') self.assertFalse(self.output.exists()) + def test_auto_selects_unprefixed_rgb_among_named_aovs_in_either_part_order(self): + for source,part in [('main-first.exr',0),('main-last.exr',2)]: + with self.subTest(source=source): + self.output=self.directory/(source+'.png') + result=self.invoke('convert',self.inputs[source],'--visualize','auto','--ocio-config','ocio://default', + '--output',self.output)[0] + chosen=result['selection']['chosen'] + self.assertEqual((chosen['part'],chosen['part_name'],chosen['group']),(part,'main','RGB')) + self.assertEqual(chosen['channels'],['R','G','B','A']) + self.assertIn('unprefixed RGB',chosen['reason']) + self.assertNotIn('visualization',result) + self.assertEqual((self.directory/'main-first.exr.png').read_bytes(),self.output.read_bytes()) + def test_auto_keeps_single_part_root_rgb_with_named_light_groups(self): + result=self.invoke('convert',self.inputs['root-with-light-groups.exr'],'--visualize','auto','--ocio-config','ocio://default', + '--output',self.output)[0] + selection=result['selection'] + self.assertEqual({c['group'] for c in selection['candidates']},{'RGB','diffuse_direct'}) + self.assertEqual(selection['chosen']['group'],'RGB') + self.assertEqual(selection['chosen']['channels'],['R','G','B']) + def test_auto_rejects_other_colour_views_and_prefixed_rgb(self): + for source,code in [('two-views.exr','ambiguous_channels'),('other-view.exr','ambiguous_parts'), + ('two-roots.exr','ambiguous_parts'),('prefixed-rgb.exr','ambiguous_parts')]: + with self.subTest(source=source): + result=self.invoke('convert',self.inputs[source],'--visualize','auto','--output',self.output,exit=4)[0] + self.assertEqual(result['error']['code'],code) + self.assertFalse(self.output.exists()) + def test_auto_keeps_primary_and_explicit_selection_priorities(self): + colour=self.invoke('convert',self.inputs['main-first.exr'],'--output',self.output,exit=4)[0] + self.assertEqual(colour['error']['code'],'ambiguous_parts') + for source,options,part,group in [ + ('root-with-light-groups.exr',['--selection-policy','root_rgb'],'main','RGB'), + ('root-with-light-groups.exr',['--part','0'],'main','RGB'), + ('main-first.exr',['--part-name','sHaDoW'],'sHaDoW','RGB'), + ('main-first.exr',['--channels','Fresnel'],'passes','Fresnel'), + ('root-with-primary.exr',[],'main','Beauty'), + ('named-primary.exr',[],'Beauty','RGB'), + ]: + with self.subTest(source=source,options=options): + result=self.invoke('convert',self.inputs[source],'--visualize','auto','--ocio-config','ocio://default', + '--output',self.output,*options)[0] + chosen=result['selection']['chosen'] + self.assertEqual((chosen['part_name'],chosen['group']),(part,group)) + self.assertEqual(chosen['primary'],part=='Beauty' or group=='Beauty') + self.output.unlink() + def test_auto_sequence_reuses_a_named_part_across_reordering_and_new_primary(self): + jobs=[self.job(name,name+'.exr',{'visualization':'auto','ocio_config':'ocio://default'},'main') + for name in ['main-first','main-last','named-primary']] + results={r['id']:r['selection'] for r in self.batch(jobs) if r['type']=='result'} + self.assertEqual(results['main-first']['lock_status'],'created') + for name,part in [('main-last',2),('named-primary',0)]: + chosen=results[name]['chosen'] + self.assertEqual((chosen['part'],chosen['part_name']),(part,'main')) + self.assertEqual(results[name]['lock_status'],'reused') def test_required_and_incompatible_options(self): cases=[('depth','Z',[]),('vector','motion',[]),('id_rgb','matID',[]),('id','object_id',['--data-range','0,1']), ('normal','N',['--data-range','1,1']),('normal','N',['--data-range','0,nan']), diff --git a/tests/test_bounded_exr.cpp b/tests/test_bounded_exr.cpp new file mode 100644 index 0000000..1bb5ef6 --- /dev/null +++ b/tests/test_bounded_exr.cpp @@ -0,0 +1,269 @@ +#include "../src/exr_rows.h" +#include +#include +#include +#include +#include +#include +#include + +namespace fs=std::filesystem; +using OIIO::ImageInput; +using OIIO::ImageOutput; +using OIIO::ImageSpec; +using OIIO::TypeDesc; +using thumbgen::detail::probe_exr_rows; + +static void require(bool ok,const std::string& message) { + if(!ok)throw std::runtime_error(message); +} + +static void fixture(const fs::path& path,const char* compression,bool tiled,bool half,bool multipart=false) { + ImageSpec s(19,17,5,half?TypeDesc::HALF:TypeDesc::FLOAT); + s.channelnames={"beauty.R","beauty.G","beauty.B","beauty.A","Z"}; + s.alpha_channel=3; + s.z_channel=4; + s.channelformats={s.format,s.format,s.format,s.format,TypeDesc::FLOAT}; + s.x=-14;s.y=-6; + s.full_x=-4;s.full_y=-10;s.full_width=27;s.full_height=22; + if(std::string_view(compression)=="zips") { + s.x+=100;s.full_x+=100; + s.y+=100;s.full_y+=100; + } + s.attribute("compression",compression); + s.attribute("Orientation",6); + if(tiled){s.tile_width=8;s.tile_height=8;s.tile_depth=1;} + std::vector pixels(std::size_t(s.width)*s.height*s.nchannels); + for(int y=0;y blank(pixels.size()); + require(writer->open(path.u8string(),2,parts),writer->geterror()); + require(writer->write_image(TypeDesc::FLOAT,blank.data()),writer->geterror()); + require(writer->open(path.u8string(),parts[1],ImageOutput::AppendSubimage),writer->geterror()); + } else require(writer->open(path.u8string(),s),writer->geterror()); + require(writer->write_image(TypeDesc::FLOAT,pixels.data()),writer->geterror()); + require(writer->close(),writer->geterror()); +} + +static void compare_rows(const fs::path& path,bool tiled,bool half,bool supported,int part=0) { + auto input=ImageInput::open(path.u8string()); + require(bool(input),"open OpenEXR fixture"); + ImageSpec spec; + require(input->seek_subimage(part,0,spec),"seek selected part"); + const auto names=std::vector{"beauty.B","beauty.R","beauty.G","beauty.A"}; + std::vector channels; + for(const auto& name:names) { + auto found=std::find(spec.channelnames.begin(),spec.channelnames.end(),name); + require(found!=spec.channelnames.end(),"missing test channel"); + channels.push_back(int(found-spec.channelnames.begin())); + } + auto probe=probe_exr_rows(path.u8string(),spec,part,channels); + require(bool(probe)==supported,"unexpected OpenEXR route"); + if(!supported)return; + const auto sample_bytes=half?2u:4u; + require(probe->read.pixel_bytes==4*sample_bytes && probe->sample_format==(half?TypeDesc::HALF:TypeDesc::FLOAT), + "selected native layout"); + auto compression=spec.get_string_attribute("compression"); + const auto strip_rows=tiled?8:compression=="zip"?std::min(16,spec.height):compression=="piz"?spec.height:1; + const auto strip_width=tiled?spec.width-spec.tile_width:spec.width; + require(probe->read.retained_bytes>=std::size_t(strip_width)*strip_rows*4*sample_bytes, + "selected strip storage is charged"); + const auto chunk_pixels=tiled?64:std::size_t(spec.width)*strip_rows; + const auto all_lane_bytes=chunk_pixels*(4*sample_bytes+4); + const auto copies=compression=="none"?1:3; + require(probe->read.codec_bytes>=8*thumbgen::detail::bounded_mib+copies*all_lane_bytes, + "all source lanes are charged in codec scratch"); + + std::vector reference(std::size_t(spec.width)*spec.height*spec.nchannels); + require(input->read_image(part,0,0,spec.nchannels,TypeDesc::FLOAT,reference.data()),input->geterror()); + input->close(); + auto rows=probe->read.open(); + std::vector native(std::size_t(spec.full_width)*3*probe->read.pixel_bytes,0xff); + std::vector converted(std::size_t(spec.full_width)*3*channels.size()); + for(int y0=0;y0read(y0,y1,native.data()); + require(OIIO::convert_pixel_values(probe->sample_format,native.data(),TypeDesc::FLOAT,converted.data(), + (y1-y0)*spec.full_width*4),"convert native read"); + for(int y=y0;y=0 && dx=0 && dyfinish(); +} + +static void incomplete_offsets(const fs::path& path) { + fixture(path,"zip",false,false); + auto input=ImageInput::open(path.u8string()); + require(bool(input),"open offset fixture"); + const auto spec=input->spec(); + input->close(); + + exr_context_t context=nullptr; + const auto filename=path.u8string(); + require(exr_start_read(&context,filename.c_str(),nullptr)==EXR_ERR_SUCCESS,"open offset metadata"); + std::uint64_t offset=0; + const auto status=exr_get_chunk_table_offset(context,0,&offset); + exr_finish(&context); + require(status==EXR_ERR_SUCCESS && offset>0,"locate offset table"); + std::fstream file(path,std::ios::binary|std::ios::in|std::ios::out); + file.seekp(std::streamoff(offset)); + const char zero[8]{}; + file.write(zero,sizeof(zero)); + file.close(); + require(bool(file),"clear first chunk offset"); + require(!probe_exr_rows(filename,spec,0,{0,1,2,3}),"incomplete chunk table must use fallback"); +} + +static void compare_output(const fs::path& lhs,const fs::path& rhs,int width,int height) { + auto read=[&](const fs::path& path) { + ImageSpec options; + options.attribute("oiio:UnassociatedAlpha",1); + auto input=ImageInput::open(path.u8string(),&options); + require(bool(input),"open paired preview"); + const auto& s=input->spec(); + require(s.width==width && s.height==height && s.nchannels==4,"oriented output layout"); + std::vector pixels(std::size_t(width)*height*4); + require(input->read_image(0,0,0,4,TypeDesc::UINT8,pixels.data()),input->geterror()); + return pixels; + }; + const auto a=read(lhs),b=read(rhs); + for(std::size_t i=0;i previous_; + static int set(const char* value) { +#ifdef _WIN32 + return _putenv_s("OCIO",value?value:""); +#else + return value?setenv("OCIO",value,1):unsetenv("OCIO"); +#endif + } +public: + explicit OcioEnvironment(const std::string& value) { + if(const char* previous=std::getenv("OCIO"))previous_=previous; + require(set(value.c_str())==0,"set project OCIO environment"); + } + ~OcioEnvironment(){set(previous_?previous_->c_str():nullptr);} +}; + +static void compare_engine(const fs::path& root,const fs::path& input,bool expect_bounded,int part=0) { + const auto config=root/"test.ocio"; + std::ofstream(config)< {name: Default, colorspace: workingRGB} +displays: + testDisplay: + - ! {name: testView, colorspace: sRGB} +colorspaces: + - ! + name: workingRGB + bitdepth: 32f + isdata: false + - ! + name: encodedInput + bitdepth: 32f + isdata: false + to_scene_reference: ! {value: [2, 2, 2, 1]} + - ! + name: sRGB + bitdepth: 32f + isdata: false + from_scene_reference: ! {value: [0.5, 0.5, 0.5, 1]} +)"; + thumbgen::Engine bounded,reference; + bool observed=false; + thumbgen::Engine::Control control; + control.planned=[&](const auto&,const auto& report) { + const bool using_rows=!report.at("footprint").at("bounded_read").is_null(); + require(using_rows==expect_bounded,"unexpected admitted preview route"); + observed=true; + }; + bounded.set_control(control); + control.planned={};control.reference_colour=true; + reference.set_control(control); + thumbgen::Job job; + job.input=input.u8string(); + OcioEnvironment environment(config.u8string()); + job.options.input_space="encodedInput"; + job.options.background="transparent"; + job.options.channels="beauty"; + job.options.part=part; + job.options.threads=1; + job.sequence_id="synthetic-sequence"; + for(int frame=0;frame<2;++frame) { + for(int pass=0;pass<2;++pass) { + job.outputs.clear(); + for(int size:{27,15}) { + auto path=root/(std::to_string(frame)+"-"+std::to_string(pass)+"-"+std::to_string(size)+".png"); + job.outputs.push_back({path.u8string(),"png",size,size,90}); + } + auto result=(pass?reference:bounded).convert(job); + require(result.at("ok").get(),result.dump()); + require(result.at("selection").at("lock_status")== (frame?"reused":"created"),"sequence lock"); + require(result.at("source").at("part")==part,"selected part index"); + require(result.at("colour").at("config_basis")=="environment","inherit project OCIO"); + require(result.at("colour").at("working_space")=="workingRGB","project OCIO working space"); + } + compare_output(root/(std::to_string(frame)+"-0-27.png"),root/(std::to_string(frame)+"-1-27.png"),22,27); + compare_output(root/(std::to_string(frame)+"-0-15.png"),root/(std::to_string(frame)+"-1-15.png"),12,15); + } + require(observed,"worker admission was observed"); +} + +int main(int argc,char** argv) { + try { + require(argc==2,"usage: test_bounded_exr EMPTY_OUTPUT_ROOT"); + const fs::path root=fs::absolute(argv[1]); + require(fs::create_directories(root),"test output root must not exist"); + for(const char* compression:{"none","rle","zips","zip","piz","pxr24"})for(bool tiled:{false,true}) { + const auto directory=root/(std::string(compression)+(tiled?"-tiled":"-scan")); + fs::create_directories(directory); + const auto input=directory/"image.exr"; + const auto name=std::string_view(compression); + const bool half=tiled || name=="rle"; + const bool supported=name!="pxr24"; + fixture(input,compression,tiled,half); + compare_rows(input,tiled,half,supported); + if(name=="zip" || name=="pxr24")compare_engine(directory,input,supported); + } + const auto multipart=root/"multipart"; + fs::create_directory(multipart); + const auto input=multipart/"image.exr"; + fixture(input,"zip",true,true,true); + compare_rows(input,true,true,true,1); + compare_engine(multipart,input,true,1); + incomplete_offsets(root/"incomplete.exr"); + std::cout<<"Bounded flat OpenEXR coverage passed\n"; + return 0; + } catch(const std::exception& error) { + std::cerr<HH", 24000, 24000) + if progressive: + return buf + # A sequential JPEG with a noninterleaved first scan also retains full + # coefficients. Its declared cost must be rejected before entropy decode. + scan = buf.index(b"\xff\xda") + return buf[:scan] + b"\xff\xda\x00\x08\x01" + buf[scan + 5:scan + 7] + b"\x00\x3f\x00\xff\xd9" + + +def png_size(path): + with Path(path).open("rb") as preview: + header = preview.read(24) + assert header[:16] == b"\x89PNG\r\n\x1a\n\0\0\0\rIHDR", path + return struct.unpack(">II", header[16:]) + + +with tempfile.TemporaryDirectory(prefix="bounded-jpeg-") as tmp: + root = Path(tmp) + subprocess.run([str(args.fixture_exe.resolve()), "--fixtures", str(root)], env=env, check=True, timeout=90) + sources = {name: root / f"{name}.jpg" for name in + ("baseline", "baseline12", "progressive", "oversized", "multiscan", "truncated", "metadata")} + for name, progressive in (("oversized", True), ("multiscan", False)): + small = root / ("small-progressive.jpg" if progressive else "small-baseline.jpg") + sources[name].write_bytes(oversized_frame(small.read_bytes(), progressive)) + sources["truncated"].write_bytes(b"\xff\xd8\xff\xe1\x00\x25Exif\0\0") + with sources["metadata"].open("wb") as handle: + handle.write(b"\xff\xd8") + for _ in range(129): + handle.write(b"\xff\xe1\xff\xff" + bytes(65533)) + results = run(root, sources, 2048, "admitted") + for name, heights in (("baseline", (512, 180)), ("baseline12", (683, 240)), ("progressive", (512, 180))): + record = results[name] + assert record["ok"] and record["execution"]["admission_mib"] < 512, record + for output, size in zip(record["outputs"], zip((1024, 360), heights)): + assert png_size(output["path"]) == size, output + print(f'{name} admission {record["execution"]["admission_mib"]:.2f} MiB') + assert results["progressive"]["colour"]["icc"]["engine"] == "skcms", results["progressive"] + for name in ("oversized", "multiscan"): + record = results[name] + assert record["error"]["code"] == "decode_limit_exceeded" and "admission_mib" not in record["execution"], record + for name in ("truncated", "metadata"): + assert results[name]["error"]["code"] == "open_failed", results[name] + rejected = run(root, {"progressive": sources["progressive"]}, 320, "rejected")["progressive"] + assert rejected["error"]["code"] == "task_memory_exceeds_budget", rejected + assert not list(root.glob("rejected-*.png")) diff --git a/tests/test_bounded_other_cli.py b/tests/test_bounded_other_cli.py new file mode 100644 index 0000000..4e50328 --- /dev/null +++ b/tests/test_bounded_other_cli.py @@ -0,0 +1,222 @@ +"""Exercise row-backed and frame-backed formats through batch admission.""" +import argparse +import json +import os +from pathlib import Path +import struct +import subprocess +import tempfile + +import jsonschema +from PIL import Image + + +COLORS = ((210, 31, 17), (35, 180, 41), (26, 47, 196), (200, 163, 33)) + + +def rows(width, bytes_per_pixel, order, encode, stride=None): + stride = stride or width * bytes_per_pixel + for a, b in order: + left = width // 2 + yield (encode(COLORS[a]) * left + encode(COLORS[b]) * (width - left)).ljust(stride, b"\0") + + +def write_bmp(path, width, height, top=False, rgba=False, compression=0): + n = 4 if rgba else 3 + stride = (width * n + 3) & ~3 + with path.open("wb") as file: + file.write(struct.pack("<2sIII", b"BM", stride * height + 54, 0, 54)) + file.write(struct.pack("" + buf = bytearray(2048) + buf[:4] = b"XPDS" if little else b"SDPX" + struct.pack_into(order + "I8sIIIII", buf, 4, len(buf), b"V2.0", len(buf) + 4 * width * height, + 0, 1664, 384, 0) + struct.pack_into(order + "HHII", buf, 768, int(mirrored), 1, width, height) + struct.pack_into(order + "BBBBHHIII", buf, 800, 50, 6, 6, 10, 1, 0, len(buf), 0, 0) + struct.pack_into(order + "II", buf, 1920, 0xffffffff, 0xffffffff) + + def pixel(rgb): + r, g, b = (value * 4 for value in rgb) + return struct.pack(order + "I", (r << 22) | (g << 12) | (b << 2)) + + quadrants = [(1, 0), (3, 2)] if mirrored else [(0, 1), (2, 3)] + with path.open("wb") as file: + file.write(buf) + for row, length in zip(rows(width, 4, quadrants, pixel), (height // 2, height - height // 2)): + for _ in range(length): + file.write(row) + + +def write_hdr(path, width, height, mirrored=False, rle=True): + def repeat(count, value): + return bytes([255, value]) * (count // 127) + (bytes([128 + count % 127, value]) if count % 127 else b"") + + with path.open("wb") as file: + direction = "-X" if mirrored else "+X" + file.write(f"#?RADIANCE\nFORMAT=32-bit_rle_rgbe\nEXPOSURE=1.0\n\n-Y {height} {direction} {width}\n".encode()) + quadrants = [(1, 0), (3, 2)] if mirrored else [(0, 1), (2, 3)] + for (left, right), lines in zip(quadrants, (height // 2, height - height // 2)): + a, b = COLORS[left] + (128,), COLORS[right] + (128,) + if rle: + row = b"\x02\x02" + struct.pack(">H", width) + row += b"".join(repeat(width // 2, x) + repeat(width - width // 2, y) for x, y in zip(a, b)) + else: + row = bytes(a) * (width // 2) + bytes(b) * (width - width // 2) + for _ in range(lines): + file.write(row) + + +def write_webp(path, width, height, orientation=1, lossless=False): + image = Image.new("RGB", (width, height)) + for i, rgb in enumerate(COLORS): + x, y = i % 2, i // 2 + image.paste(rgb, (x * width // 2, y * height // 2, + width // 2 if x == 0 else width, height // 2 if y == 0 else height)) + options = {} + if orientation != 1: + exif = Image.Exif() + exif[274] = orientation + options["exif"] = exif.tobytes() + image.save(path, quality=95, method=0, lossless=lossless, **options) + + +def run(args, root, sources, memory, decode, prefix): + jobs = [ + dict(id=name, input=str(path), outputs=[ + dict(path=str(root / f"{prefix}-{name}-{width}.png"), size=[width, height], format="png") + for width, height in ((640, 480), (192, 128))]) + for name, path in sources.items() + ] + manifest = dict(schema_version=1, defaults=dict(threads=1, max_decode_mib=decode), jobs=jobs, + execution=dict(workers=1, thread_budget=1, memory_budget_mib=memory)) + path = root / "jobs.json" + path.write_text(json.dumps(manifest), encoding="utf-8") + env = dict(os.environ) + env.pop("OCIO", None) + key = "PATH" if os.name == "nt" else "LD_LIBRARY_PATH" + env[key] = str(args.runtime_dir.resolve()) + os.pathsep + env.get(key, "") + completed = subprocess.run([str(args.exe.resolve()), "batch", "--manifest", str(path), "--json"], + env=env, capture_output=True, text=True, timeout=180) + validator = jsonschema.Draft202012Validator( + json.loads((args.schema_dir / "protocol-v1.schema.json").read_text(encoding="utf-8"))) + results = {} + for line in completed.stdout.splitlines(): + row = json.loads(line) + validator.validate(row) + if row["type"] == "result": + results[row["id"]] = row + assert results.keys() == sources.keys(), (completed.stdout, completed.stderr) + return results + + +def corners(preview): + return [preview.getpixel((preview.width * x // 4, preview.height * y // 4))[:3] + for y in (1, 3) for x in (1, 3)] + + +def check(record, sizes, colors, tolerance): + assert record["ok"], record + for output, size in zip(record["outputs"], sizes): + with Image.open(output["path"]).convert("RGB") as preview: + assert preview.size == size, output + actual = corners(preview) + assert max(abs(a - b) for val, ref in zip(actual, colors) for a, b in zip(val, ref)) <= tolerance, actual + + +def main(): + parser = argparse.ArgumentParser() + parser.add_argument("--exe", type=Path, required=True) + parser.add_argument("--runtime-dir", type=Path, required=True) + parser.add_argument("--schema-dir", type=Path, required=True) + args = parser.parse_args() + with tempfile.TemporaryDirectory(prefix="bounded-formats-") as tmp: + root = Path(tmp) + writers = dict(hdr=write_hdr, dpx=write_dpx, bmp=write_bmp, webp=write_webp, tga=write_tga) + large = {name: root / f"large.{name}" for name in writers} + for name, path in large.items(): + writers[name](path, 12000, 6000) + results = run(args, root, large, 768, 512, "bounded") + # HDR stores linear Rec.709, which is encoded into display sRGB. + hdr_colors = tuple(tuple(round(255 * (1.055 * (value / 256) ** (1 / 2.4) - 0.055)) + for value in rgb) for rgb in COLORS) + for name, record in results.items(): + check(record, [(640, 320), (192, 96)], hdr_colors if name == "hdr" else COLORS, 5) + admission = record["execution"]["admission_mib"] + assert admission < (430 if name in ("tga", "webp") else 150), record + if name in ("tga", "webp"): + assert admission > 206, record # The scheduler must account for the RGB frame. + print(f"{name} admission {admission:.2f} MiB") + for name, record in run(args, root, {k: large[k] for k in ("webp", "tga")}, 512, 512, "rejected").items(): + assert record["error"]["code"] == "task_memory_exceeds_budget", (name, record) + assert not list(root.glob("rejected-*.png")) + + small = {name: root / f"small.{name}" for name in writers} + variants = dict(hdr=dict(mirrored=True, rle=False), dpx=dict(mirrored=True, little=False), + bmp=dict(top=True, rgba=True), webp=dict(orientation=6), + tga=dict(top=True, right=True)) + for name, path in small.items(): + writers[name](path, 42, 26, **variants[name]) + lossless = root / "lossless.webp" + write_webp(lossless, 42, 26, lossless=True) + for name, record in run(args, root, dict(small, lossless=lossless), 512, 512, "small").items(): + rotated = name == "webp" + color = hdr_colors if name == "hdr" else [COLORS[i] for i in (2, 0, 3, 1)] if rotated else COLORS + check(record, [(26, 42) if rotated else (42, 26)] * 2, color, 5) + + malformed = {name: root / f"bad.{name}" for name in writers} + for name, path in malformed.items(): + path.write_bytes(small[name].read_bytes()[:12]) + for name, record in run(args, root, malformed, 512, 512, "malformed").items(): + assert record["error"]["code"] == "open_failed", (name, record) + rejected = {"bmp-rle": root / "oversized.bmp", "tga-rle": root / "oversized.tga", + "webp-canvas": root / "oversized.webp", "webp-source": root / "large-source.webp", + "dpx-metadata": root / "large-header.dpx"} + write_bmp(rejected["bmp-rle"], 12000, 6000, compression=1) + write_tga(rejected["tga-rle"], 12000, 6000, rle=True) + data = bytearray(small["webp"].read_bytes()) + canvas = data.index(b"VP8X") + 12 + data[canvas:canvas + 6] = (65535).to_bytes(3, "little") * 2 + rejected["webp-canvas"].write_bytes(data) + with rejected["webp-source"].open("wb") as file: + file.write(small["webp"].read_bytes()) + file.truncate(65 * 1024 * 1024) + data = bytearray(small["dpx"].read_bytes()) + size = 5 * 1024 * 1024 + struct.pack_into(">I", data, 32, size) + with rejected["dpx-metadata"].open("wb") as file: + file.write(data) + file.truncate(2048 + size) + for name, record in run(args, root, rejected, 512, 64, "oversized").items(): + assert record["error"]["code"] == "decode_limit_exceeded", (name, record) + assert "admission_mib" not in record["execution"], (name, record) + + +if __name__ == "__main__": + main() diff --git a/tests/test_bounded_png_tiff_cli.py b/tests/test_bounded_png_tiff_cli.py new file mode 100644 index 0000000..6e30302 --- /dev/null +++ b/tests/test_bounded_png_tiff_cli.py @@ -0,0 +1,287 @@ +"""Validate bounded PNG/TIFF previews against the full-frame colour path.""" +import argparse +import json +import os +from pathlib import Path +import struct +import subprocess +import tempfile +import zlib + +import jsonschema +from PIL import Image, ImageChops, ImageCms, ImageStat + + +def chunk(name, data): + return struct.pack(">I", len(data)) + name + data + struct.pack(">I", zlib.crc32(name + data)) + + +def pixel(x, y, channels): + values = ((x * 7 + y * 3) % 256, (x * 2 + y * 11) % 256, ((x + y) * 13) % 256) + return values + (43 + 172 * ((x + y) % 2),) if channels == 4 else values + + +def packed_row(cells, y, channels, bits, endian, associated=False): + samples = [] + limit = (1 << bits) - 1 + for x in cells: + if channels >= 3: + samples.extend(value * (limit // 255) for value in pixel(x, y, channels)) + else: + gray = (x * 1823 + y * 771 + 153) & limit + alpha = ((x + y) % 5) * limit // 4 + samples.append(gray * alpha // limit if associated else gray) + if channels == 2: + samples.append(alpha) + return bytes(samples) if bits == 8 else struct.pack(f"{endian}{len(samples)}H", *samples) + + +def gray_profile(): + """Synthetic D50 grayscale display profile with a gamma 1.75 curve.""" + white = struct.pack(">3i", *(round(v * 65536) for v in (0.9642, 1, 0.8249))) + name = b"Synthetic gray\0" + tags = [(b"desc", b"desc" + bytes(4) + struct.pack(">I", len(name)) + name + bytes(78)), + (b"wtpt", b"XYZ " + bytes(4) + white), + (b"kTRC", b"curv" + bytes(4) + struct.pack(">IH", 1, 448))] + header = bytearray(128) + header[8:24] = b"\x02\x10\0\0mntrGRAYXYZ " + struct.pack_into(">6H", header, 24, 2026, 1, 1, 0, 0, 0) + header[36:40] = b"acsp" + header[68:80] = white + table = bytearray(struct.pack(">I", len(tags))) + body = bytearray() + for tag, data in tags: + table += struct.pack(">4sII", tag, 132 + 12 * len(tags) + len(body), len(data)) + body += data + bytes(-len(data) % 4) + struct.pack_into(">I", header, 0, len(header) + len(table) + len(body)) + return bytes(header + table + body) + + +def write_png(path, width, height, channels=3, bits=8, interlaced=False, profile=b"", offset=None, + header_only=False, gamma=None): + ihdr = struct.pack(">IIBBBBB", width, height, bits, {1: 0, 2: 4, 3: 2, 4: 6}[channels], 0, 0, interlaced) + x_block, y_block = max(1, width // 47), max(1, height // 47) + with path.open("wb") as file: + file.write(b"\x89PNG\r\n\x1a\n" + chunk(b"IHDR", ihdr)) + if gamma is not None: + file.write(chunk(b"gAMA", struct.pack(">I", gamma))) + if profile: + file.write(chunk(b"iCCP", b"Synthetic profile\x00\x00" + zlib.compress(profile))) + if offset: + file.write(chunk(b"oFFs", struct.pack(">iiB", *offset, 0))) + if not header_only: + passes = [(0, 0, 1, 1)] + if interlaced: + passes = [(0, 0, 8, 8), (4, 0, 8, 8), (0, 4, 4, 8), (2, 0, 4, 4), + (0, 2, 2, 4), (1, 0, 2, 2), (0, 1, 1, 2)] + compressor = zlib.compressobj(1) + for x0, y0, dx, dy in passes: + if x0 >= width: + continue + rows = {} + for y in range(y0, height, dy): + band = y // y_block + if band not in rows: + samples = packed_row((x // x_block for x in range(x0, width, dx)), band, channels, bits, ">") + rows = {band: b"\0" + samples} + compressed = compressor.compress(rows[band]) + if compressed: + file.write(chunk(b"IDAT", compressed)) + file.write(chunk(b"IDAT", compressor.flush())) + file.write(chunk(b"IEND", b"")) + + +def write_tiff(path, width, height, block, header_only=False, *, tiled=True, channels=3, bits=8, + associated=False, profile=b"", orientation=1, white=False): + # Classic little-endian Deflate. Tiles include right and bottom padding. + block_width = block if tiled else width + x_step, y_step = max(1, width // 47), max(1, height // 47) + with path.open("w+b") as file: + file.write(b"II" + struct.pack("= 3 else int(not white)]), (274, 3, [orientation]), + (277, 3, [channels]), (284, 3, [1])] + if tiled: + tags += [(322, 4, [block]), (323, 4, [block]), (324, 4, offsets), (325, 4, counts)] + else: + tags += [(273, 4, offsets), (278, 4, [block]), (279, 4, counts)] + if channels in (2, 4): + tags.append((338, 3, [1 if associated else 2])) + if profile: + tags.append((34675, 7, profile)) + tags.sort() + directory = [struct.pack("([&]{auto invalid=incremental;invalid.channel_span=4;estimate_memory(invalid);}); auto bounded8=incremental;bounded8.source_sample_bytes=1;bounded8.source_pixel_bytes=bounded8.selected_channels; require(estimate_memory(bounded8).total==bounded.total,"UINT8 C2 must retain the declared UINT16 worst-case reserve"); + auto native=fast; + const auto single=bounded_read_memory(5184,3456,3,3,4*bounded_mib,12*bounded_mib,0,64*1024,{{960,640}}); + native.bounded=bounded_read_memory(5184,3456,3,3,4*bounded_mib,12*bounded_mib,0,64*1024,{{960,640},{320,200}}); + require(native.bounded.output-single.output==320ULL*200*3*sizeof(float),"simultaneously retained second output omitted"); + const auto native_estimate=estimate_memory(native); + require(native_estimate.incremental==bounded_total(native.bounded)+native_estimate.margin && + native_estimate.total==native_estimate.incremental+native_estimate.worker,"native read admission charged an inconsistent footprint"); + rejects([]{bounded_read_memory(100,100,3,3,std::numeric_limits::max(),0,0,1024,{{10,10}});}); rejects([&]{auto invalid=incremental;invalid.data_width=invalid.display_width=1;estimate_memory(invalid);}); rejects([&]{auto invalid=incremental;invalid.output_width=2000;estimate_memory(invalid);}); rejects([]{c2_memory(65537,2000,4,425,212);}); diff --git a/tests/test_color_input.py b/tests/test_color_input.py index a5c4af2..c47bfe3 100644 --- a/tests/test_color_input.py +++ b/tests/test_color_input.py @@ -25,7 +25,8 @@ for name in ('exe','probe-exe','runtime-dir','schema-dir'): parser.add_argument('--'+name,type=Path,required=True) args,remaining=parser.parse_known_args() -env=dict(os.environ,OCIO='') +env=dict(os.environ) +env.pop('OCIO',None) key='PATH' if os.name=='nt' else 'LD_LIBRARY_PATH' env[key]=str(args.runtime_dir.resolve())+os.pathsep+env.get(key,'') validator=Draft202012Validator(json.loads((args.schema_dir/'protocol-v1.schema.json').read_text(encoding='utf-8'))) @@ -175,12 +176,13 @@ def setUp(self): def tearDown(self):self.temp.cleanup() def fixture(self,name,data): path=self.root/name;path.write_bytes(data);return path - def run_json(self,exe,command,exit=0): + def run_json(self,exe,command,exit=0,*,ocio=None): command=[str(exe),*map(str,command)] + child_env=env if ocio is None else dict(env,OCIO=str(ocio)) started=time.monotonic() print(f'child start: {command!r}',file=sys.stderr,flush=True) try: - run=subprocess.run(command,env=env,capture_output=True,text=True,encoding='utf-8',timeout=45) + run=subprocess.run(command,env=child_env,capture_output=True,text=True,encoding='utf-8',timeout=45) except BaseException as error: print(f'child exception: {error!r}',file=sys.stderr,flush=True) raise @@ -192,6 +194,29 @@ def run_json(self,exe,command,exit=0): except json.JSONDecodeError as error:self.fail(f'invalid JSON: {error}\n{diagnostic}') self.assertTrue(rows,f'no JSON records\n{diagnostic}') return rows + def project_config(self): + return self.fixture('project.ocio',b"""ocio_profile_version: 2 +roles: + scene_linear: working +file_rules: + - ! {name: Default, colorspace: working} +displays: + Preview: + - ! {name: Standard, colorspace: Project Output} +colorspaces: + - ! {name: working, aliases: [linear, lin_rec709_scene], bitdepth: 32f, isdata: false} + - ! + name: Project Output + aliases: [sRGB] + bitdepth: 32f + isdata: false + from_scene_reference: ! {value: [0.5, 0.5, 0.5, 1]} +""") + def convert_config(self,path,*options,ocio=None,exit=0): + result=self.run_json(args.exe,['convert',path,'--output',self.target,'--size','8','--threads',1,'--json',*options], + exit,ocio=ocio)[0] + validator.validate(result) + return result def convert(self,path,space=None,exit=0): before=hashlib.sha256(path.read_bytes()).digest() command=['convert',path,'--output',self.target,'--format','png','--size','8x8', @@ -347,26 +372,69 @@ def test_webp_icc_independent_reference(self): def riff_chunk(tag,payload):return tag+struct.pack(' {name: Default, colorspace: working} -displays: - test: - - ! {name: test, colorspace: working} -colorspaces: - - ! {name: working, family: test, bitdepth: 32f, isdata: false} -""",encoding='utf-8') + config=self.project_config() path=self.fixture('custom.png',png(profile())) - result=self.run_json(args.exe,['convert',path,'--output',self.target,'--ocio-config',config,'--json'],4)[0] - validator.validate(result);self.assertEqual(result['error']['code'],'colour_input_unsupported');self.assertIn('bridge',result['error']['message']) + for options in [('--ocio-config',config),('--display','Preview','--view','Standard')]: + with self.subTest(options=options): + result=self.convert_config(path,*options,ocio=config,exit=4) + self.assertEqual(result['error']['code'],'colour_input_unsupported') + self.assertIn('bridge',result['error']['message']) + separated=self.fixture('separated.tif',tiff(cmyk=True,icc=cmyk_profile())) + result=self.convert_config(separated,ocio=config,exit=4) + self.assertEqual(result['colour']['config_basis'],'environment') + self.assertEqual(result['error']['code'],'colour_input_unsupported') + self.assertIn('bridge',result['error']['message']) + # OIIO infers interop IDs from aliases even when OCIO declares none. + config.write_text(config.read_text().replace('aliases: [sRGB]','aliases: [sRGB, srgb_rec709_scene]'),encoding='utf-8') + result=self.convert_config(path,'--ocio-config',config,exit=4) + self.assertEqual(result['error']['code'],'colour_input_unsupported') + self.assertIn('bridge',result['error']['message']) + result=self.convert_config(path,'--ocio-config',self.root/'missing.ocio',exit=4) + self.assertEqual(result['error']['code'],'colour_config_failed') + self.assertFalse(self.target.exists()) def test_declared_bridge_to_distinct_project_linear(self): config=self.root/'bridge.ocio' config.write_text("""ocio_profile_version: 2 @@ -391,10 +459,33 @@ def test_declared_bridge_to_distinct_project_linear(self): to_scene_reference: ! {gamma: [2.4, 2.4, 2.4, 1], offset: [0.055, 0.055, 0.055, 0]} """,encoding='utf-8') path=self.fixture('bridge.png',png(profile())) - result=self.run_json(args.exe,['convert',path,'--output',self.target,'--ocio-config',config,'--json'])[0] - validator.validate(result);self.assertEqual(result['colour']['working_space'],'project') - for pixel in read_png(self.target)[2]: - for actual,wanted in zip(pixel,(137,188,225)):self.assertLessEqual(abs(actual-wanted),1) + legacy=config.read_text(encoding='utf-8') + standard=legacy.replace('colorspace: srgb_rec709_scene','colorspace: Scene Texture').replace( + 'name: srgb_rec709_scene\n aliases: [sRGB]', + 'name: Scene Texture\n aliases: [srgb_rec709_scene]\n interop_id: srgb_rec709_scene') + project_output=standard+""" - ! + name: Project Output + aliases: [sRGB] + bitdepth: 32f + isdata: false + from_scene_reference: ! {value: [0.5, 0.5, 0.5, 1]} +""" + cases=[(legacy,'srgb_rec709_scene','srgb_rec709_scene',[],(137,188,225)), + (standard,'Scene Texture','Scene Texture',[],(137,188,225)), + (project_output,'Scene Texture','Project Output',[],(128,181,221)), + (project_output,'Scene Texture','',['--display','test','--view','test'],(137,188,225))] + for content,bridge,output,options,expected in cases: + with self.subTest(bridge=bridge,output=output): + config.write_text(content,encoding='utf-8') + result=self.convert_config(path,'--ocio-config',config,*options,ocio=self.project_config()) + self.assertEqual(result['colour']['config_basis'],'explicit') + self.assertEqual(result['colour']['ocio_config'],str(config)) + self.assertEqual(result['colour']['input_space'],bridge) + self.assertEqual(result['colour']['working_space'],'project') + self.assertEqual(result['colour']['output_space'],output) + for pixel in read_png(self.target)[2]: + for actual,wanted in zip(pixel,expected):self.assertLessEqual(abs(actual-wanted),1) + self.target.unlink() def test_associated_tiff_alpha_and_orientation(self): path=self.fixture('associated.tif',tiff(icc=profile(),associated=True,orientation=6)) result=self.convert_transparent(path);self.assertTrue(result['ok'],result) diff --git a/tests/test_cryptomatte.cpp b/tests/test_cryptomatte.cpp index 76795ee..2242ba1 100644 --- a/tests/test_cryptomatte.cpp +++ b/tests/test_cryptomatte.cpp @@ -42,6 +42,52 @@ static void metadata(OIIO::ImageSpec& spec,const std::string& prefix="cryptomatt spec.attribute(prefix+"/name","Object");spec.attribute(prefix+"/hash","MurmurHash3_32");spec.attribute(prefix+"/conversion","uint32_to_float32"); spec.attribute("DateTime","2000:01:01 00:00:00"); } +static void object_family_fixtures(const fs::path& root,Json& files) { + auto save=[&](const char* fixture,const char* object,const char* secondary) { + const std::string family=object,other_family=secondary,kind=fixture; + const auto path=(root/(kind+".exr")).u8string(); + OIIO::ImageSpec parts[2]; + for(int part=0;part<2;++part) { + std::vector channels; + for(char c:std::string("RGBA"))channels.push_back(family+(part?"01.":"00.")+c); + if(part)for(char c:std::string("RGBA"))channels.push_back(other_family+"00."+c); + if(part && kind=="beauty_and_families")channels.insert(channels.end(),{"R","G","B"}); + if(part && kind=="object_bad_layout")channels.erase(channels.begin()+3); + parts[part]=OIIO::ImageSpec(2,2,int(channels.size()),OIIO::TypeDesc::FLOAT); + parts[part].channelnames=std::move(channels); + parts[part].attribute("oiio:subimagename",part?"second":"first"); + } + metadata(parts[0]); + parts[0].attribute("cryptomatte/test123/name",family); + if(kind=="object_bad_metadata")parts[0].attribute("cryptomatte/test123/hash","wrong_hash"); + metadata(parts[1],"cryptomatte/test456"); + parts[1].attribute("cryptomatte/test456/name",other_family); + auto out=OIIO::ImageOutput::create(path);require(bool(out),OIIO::geterror()); + require(out->open(path,2,parts),out->geterror()); + for(int part=0;part<2;++part) { + if(part)require(out->open(path,parts[part],OIIO::ImageOutput::AppendSubimage),out->geterror()); + std::vector pixels(4*parts[part].nchannels); + for(std::size_t c=0;cwrite_image(OIIO::TypeDesc::FLOAT,pixels.data()),out->geterror()); + } + require(out->close(),out->geterror()); + files[kind]=path; + }; + save("object_underscore","CRYPTO_OBJECT","crypto_material"); + save("object_camel","CryptoObject","CryptoMaterial"); + save("mislabeled_object","Crypto_Object_Extra","CryptoMaterial"); + save("two_objects","CryptoObject","crypto_object"); + save("object_bad_metadata","CryptoObject","CryptoMaterial"); + save("object_bad_layout","CryptoObject","CryptoMaterial"); + save("beauty_and_families","CryptoObject","CryptoMaterial"); +} static Json fixtures(const fs::path& root) { require(fs::create_directory(root),"fixture directory already exists");Json result; for(const std::string kind:{"valid","with_beauty","multiple_families","bad","half_coverage","half_id","odd","gap","no_metadata","bad_hash","sidecar","legacy","many","window","oriented","missing_last","identity","strip_float","strip_half","strip_bad","strip_window","strip_tiled","strip_interleaved","strip_zips"}) { @@ -120,7 +166,9 @@ static Json fixtures(const fs::path& root) { std::memcpy(pixels,&bunny,sizeof(bunny));pixels[1]=0.25f; require(output->write_image(OIIO::TypeDesc::FLOAT,pixels),output->geterror());require(output->open(path.u8string(),parts[1],OIIO::ImageOutput::AppendSubimage),output->geterror()); std::memcpy(pixels,&other,sizeof(other));pixels[1]=0.75f; - require(output->write_image(OIIO::TypeDesc::FLOAT,pixels),output->geterror());require(output->close(),output->geterror());result["split"]=path.u8string();return result; + require(output->write_image(OIIO::TypeDesc::FLOAT,pixels),output->geterror());require(output->close(),output->geterror());result["split"]=path.u8string(); + object_family_fixtures(root,result); + return result; } static int run(const std::vector& args) { try { diff --git a/tests/test_cryptomatte_cli.py b/tests/test_cryptomatte_cli.py index 2604aeb..f9bdc26 100644 --- a/tests/test_cryptomatte_cli.py +++ b/tests/test_cryptomatte_cli.py @@ -167,6 +167,43 @@ def test_auto_reports_ambiguity_and_invalid_layout(self): result=self.invoke('convert',self.inputs[source],'--visualize','auto','--output',self.output,exit=4)[0] self.assertEqual(result['error']['code'],code) self.assertFalse(self.output.exists()) + def test_auto_prefers_semantic_object_family_and_combines_parts(self): + for source,family in [('object_underscore','CRYPTO_OBJECT'),('object_camel','CryptoObject')]: + with self.subTest(source=source): + self.output=self.directory/(source+'.png') + result=self.invoke('convert',self.inputs[source],'--visualize','auto','--output',self.output)[0] + self.assertEqual(result['cryptomatte']['layers'],[family+'00',family+'01']) + chosen=result['selection']['chosen'] + self.assertEqual(chosen['group'],family) + self.assertIn('object family',chosen['reason']) + self.assertEqual(png(self.output),(2,2,[EXPECTED[0]]*4)) + def test_auto_rejects_ambiguous_or_malformed_object_families(self): + cases=[('mislabeled_object','ambiguous_channels'),('two_objects','ambiguous_channels'), + ('object_bad_metadata','cryptomatte_metadata_invalid'),('object_bad_layout','cryptomatte_layout_unsupported')] + for source,code in cases: + with self.subTest(source=source): + result=self.invoke('convert',self.inputs[source],'--visualize','auto','--output',self.output,exit=4)[0] + self.assertEqual(result['error']['code'],code) + self.assertFalse(self.output.exists()) + def test_explicit_material_overrides_preferred_or_malformed_object(self): + for source in ['object_camel','object_bad_metadata','object_bad_layout']: + with self.subTest(source=source): + self.output=self.directory/(source+'.png') + result=self.invoke('convert',self.inputs[source],'--visualize','cryptomatte','--channels','CryptoMaterial', + '--output',self.output)[0] + self.assertEqual(result['selection']['chosen']['group'],'CryptoMaterial') + self.assertEqual(result['cryptomatte']['layers'],['CryptoMaterial00']) + self.assertEqual(png(self.output),(2,2,[EXPECTED[7]]*4)) + def test_auto_keeps_colour_over_semantic_object_family(self): + result=self.invoke('convert',self.inputs['beauty_and_families'],'--visualize','auto','--ocio-config','ocio://default', + '--output',self.output)[0] + self.assertEqual(result['selection']['chosen']['group'],'RGB') + self.assertNotIn('cryptomatte',result) + def test_root_rgb_policy_keeps_multiple_families_ambiguous(self): + result=self.invoke('convert',self.inputs['object_camel'],'--visualize','auto','--selection-policy','root_rgb', + '--output',self.output,exit=4)[0] + self.assertEqual(result['error']['code'],'ambiguous_channels') + self.assertFalse(self.output.exists()) def test_auto_sequence_preserves_first_preview_kind(self): jobs=[self.job(name,source,visualization='auto',channels='') for name,source in [('first','split'),('changed','with_beauty'),('recovered','split')]] diff --git a/tests/test_isolated.cpp b/tests/test_isolated.cpp index 6b9213b..1f1d88b 100644 --- a/tests/test_isolated.cpp +++ b/tests/test_isolated.cpp @@ -278,7 +278,7 @@ static int test_main(const std::vector& args) { auto c2normal=c2job("c2-normal");rows=run({c2normal,c2job("c2-crash"),c2job("c2-after-crash")}); require(rows[0]["ok"]==true && rows[0]["colour"]["processing"]=="integer-linear-stream-v1" && rows[1]["error"]["code"]=="worker_crashed" && rows[2]["ok"]==true,rows.dump()); rows=run({c2job("c2-partial",2),c2job("c2-protocol"),c2job("c2-after-protocol")}); - require(rows[0]["colour"]["processing"]=="integer-linear-v1" && !fs::exists(root/"c2-partial"/"source.png.c2-allocated") && rows[0]["status"]=="partial" && rows[0]["outputs"][0]["status"]=="success" && rows[0]["outputs"][1]["error"]["code"]=="worker_crashed" && rows[1]["error"]["code"]=="worker_protocol_error" && rows[2]["ok"]==true,rows.dump()); + require(rows[0]["colour"]["processing"]=="integer-linear-v1" && fs::exists(root/"c2-partial"/"source.png.c2-allocated") && rows[0]["status"]=="partial" && rows[0]["outputs"][0]["status"]=="success" && rows[0]["outputs"][1]["error"]["code"]=="worker_crashed" && rows[1]["error"]["code"]=="worker_protocol_error" && rows[2]["ok"]==true,rows.dump()); auto c2changed=c2job("c2-source-change");rows=run({c2changed});require(rows[0]["error"]["code"]=="source_changed" && rows[0]["source_check"]["stable"]==false,rows.dump()); {std::ofstream restore(fs::u8path(c2changed.input),std::ios::binary);restore< +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +namespace fs=std::filesystem; +namespace { +void require(bool ok,const std::string& message){if(!ok)throw std::runtime_error(message);} +struct Temp { + fs::path path=fs::temp_directory_path()/("thumbgen-jpeg-rows-"+std::to_string(std::chrono::steady_clock::now().time_since_epoch().count())); + Temp(){fs::create_directory(path);} + ~Temp(){std::error_code error;fs::remove_all(path,error);} +}; +void write_jpeg(const fs::path& path,const OIIO::ImageSpec& spec){ + const int channels=spec.nchannels; + auto out=OIIO::ImageOutput::create(path.u8string()); + require(out && out->open(path.u8string(),spec),OIIO::geterror()); + std::vector row(std::size_t(spec.width)*channels); + for(int y=0;y((x/11+y/19+c*61)%256); + require(out->write_scanline(y,0,spec.format,row.data()),out->geterror()); + } + require(out->close(),out->geterror()); +} +void write_batch_fixtures(const fs::path& root){ + OIIO::ImageSpec spec(16384,8192,3,OIIO::TypeDesc::UINT8); + spec.attribute("CompressionQuality",87); + spec.attribute("jpeg:subsampling","4:2:0"); + write_jpeg(root/"baseline.jpg",spec); + spec.width=spec.full_width=12288; + write_jpeg(root/"baseline12.jpg",spec); + spec.width=spec.full_width=41;spec.height=spec.full_height=37; + write_jpeg(root/"small-baseline.jpg",spec); + spec.attribute("jpeg:progressive",1); + write_jpeg(root/"small-progressive.jpg",spec); + + auto profile=std::unique_ptr(cmsCreate_sRGBProfile(),cmsCloseProfile); + cmsUInt32Number size=0; + require(profile && cmsSaveProfileToMem(profile.get(),nullptr,&size) && size>0,"could not size synthetic ICC"); + std::vector bytes(size); + require(cmsSaveProfileToMem(profile.get(),bytes.data(),&size),"could not serialize synthetic ICC"); + spec.attribute("ICCProfile",OIIO::TypeDesc(OIIO::TypeDesc::UINT8,int(size)),bytes.data()); + spec.width=spec.full_width=12000;spec.height=spec.full_height=6000; + write_jpeg(root/"progressive.jpg",spec); +} +void compare(const thumbgen::Json& a,const thumbgen::Json& b) { + OIIO::ImageBuf x(a.at("path").get()),y(b.at("path").get()); + require(x.read(0,0,true,OIIO::TypeDesc::UINT8) && y.read(0,0,true,OIIO::TypeDesc::UINT8),"readback failed"); + require(x.spec().width==y.spec().width && x.spec().height==y.spec().height && + x.nchannels()==y.nchannels(),"dimensions differ from full decode"); + const auto* xp=static_cast(x.localpixels()); + const auto* yp=static_cast(y.localpixels()); + int max_error=0; + double abs_error=0; + for(std::size_t i=0;i,3>{{{3,1},{3,6},{1,8}}}){ + const auto source=root.path/"source.jpg"; + OIIO::ImageSpec spec(4097,2001,components,OIIO::TypeDesc::UINT8); + spec.attribute("Orientation",orientation); + write_jpeg(source,spec); + thumbgen::Job job; + job.input=source.u8string();job.options.threads=1;job.options.input_space="sRGB"; + job.outputs={{(root.path/"bounded-large.png").u8string(),"png",641,479,90,"replace"}, + {(root.path/"bounded-small.png").u8string(),"png",173,151,90,"replace"}}; + bool admitted=false; + int allocations=0,decodes=0; + thumbgen::Engine engine([&](const std::string& phase,const thumbgen::Job&){ + if(phase=="c2_allocate"){require(admitted,"bounded allocation preceded admission");++allocations;} + if(phase=="decoded")++decodes; + }); + thumbgen::Engine::Control control; + control.planned=[&](const thumbgen::Job& requested,const thumbgen::Json& plan){ + require(plan.at("footprint").at("bounded_read").is_null()==(requested.outputs.size()!=2),plan.dump()); + admitted=true; + }; + engine.set_control(control); + const auto actual=engine.convert(job); + require(actual.value("ok",false) && allocations==1 && decodes==1,actual.dump()); + if(orientation>=5)require(actual["outputs"][0]["width"] +#include +#include +#include +#include + +namespace fs=std::filesystem; +namespace { +using namespace thumbgen::detail; +void require(bool ok,const std::string& reason) { + if(!ok)throw std::runtime_error(reason); +} +struct Temp { + fs::path path=fs::temp_directory_path()/("thumbgen-native-rows-"+ + std::to_string(std::chrono::steady_clock::now().time_since_epoch().count())); + Temp(){fs::create_directory(path);} + ~Temp(){std::error_code error;fs::remove_all(path,error);} +}; + +void compare_rows(const fs::path& path,OIIO::ImageSpec spec,int orientation, + const char* compression,bool frame_buffered) { + spec.attribute("Orientation",orientation); + spec.attribute("compression",compression); + spec.attribute("oiio:UnassociatedAlpha",1); + auto out=OIIO::ImageOutput::create(path.u8string()); + require(out && out->open(path.u8string(),spec),"fixture open failed"); + std::vector values(std::size_t(spec.width)*spec.height*spec.nchannels); + for(int y=0;ywrite_image(OIIO::TypeDesc::FLOAT,values.data()),out->geterror()); + require(out->close(),out->geterror()); + + OIIO::ImageSpec config; + config.attribute("oiio:UnassociatedAlpha",1); + auto input=OIIO::ImageInput::open(path.u8string(),&config); + require(bool(input),OIIO::geterror()); + const auto expected=input->spec(); + const auto probe=probe_other_rows(path.u8string(),fs::file_size(path),512*bounded_mib, + config,std::numeric_limits::max()); + require(probe && probe->spec && probe->read.open,"no bounded reader for "+path.filename().u8string()); + const auto& actual=*probe->spec; + require(actual.width==expected.width && actual.height==expected.height && + actual.format==expected.format && actual.channelnames==expected.channelnames && + actual.get_string_attribute("oiio:ColorSpace")==expected.get_string_attribute("oiio:ColorSpace") && + actual.get_int_attribute("Orientation",1)==expected.get_int_attribute("Orientation",1) && + actual.get_int_attribute("oiio:UnassociatedAlpha",0)==expected.get_int_attribute("oiio:UnassociatedAlpha",0), + "metadata differs from plugin"); + require(probe->read.pixel_bytes==actual.pixel_bytes() && + probe->read.retained_bytes==(frame_buffered?actual.image_bytes():0) && + probe->fallback_codec_bytes==probe->read.retained_bytes+probe->read.codec_bytes, + "incorrect codec admission"); + std::vector reference(actual.image_bytes()),pixels(actual.image_bytes()); + require(input->read_image(0,0,0,actual.nchannels,actual.format,reference.data()),input->geterror()); + input->close(); + auto reader=probe->read.open(); + bool refused=false; + try {reader->read(1,2,pixels.data());}catch(const FileFailure& error){refused=error.code=="decode_failed";} + require(refused,"accepted noncontiguous read"); + reader->read(0,2,pixels.data()); + reader->read(2,actual.height,pixels.data()+2*actual.scanline_bytes()); + reader->finish(); + require(pixels==reference,"bounded row samples differ from full native decode"); +} +} + +int main() try { + Temp temp; + using OIIO::ImageSpec; + using OIIO::TypeDesc; + compare_rows(temp.path/"source.hdr",ImageSpec(27,13,3,TypeDesc::FLOAT),2,"none",false); + for(const int bits:{8,10,12,16}) { + ImageSpec spec(27,13,3,bits==8?TypeDesc::UINT8:TypeDesc::UINT16); + spec.attribute("oiio:BitsPerSample",bits); + compare_rows(temp.path/("source-"+std::to_string(bits)+".dpx"),spec,2,"none",false); + } + compare_rows(temp.path/"source.bmp",ImageSpec(27,13,4,TypeDesc::UINT8),1,"none",false); + compare_rows(temp.path/"source.tga",ImageSpec(27,13,4,TypeDesc::UINT8),1,"none",true); + compare_rows(temp.path/"source.webp",ImageSpec(27,13,4,TypeDesc::UINT8),1,"webp:95",true); + return 0; +} catch(const std::exception& error) { + std::cerr<();need(!saw_row || y>last_row,"source repeated or rewound");last_row=y;saw_row=true;} const bool stream=result.value("colour",Json::object()).value("processing",std::string{})=="integer-linear-stream-v1"; - if(c.count==2)need(!stream && c2_allocations==0 && !plan["footprint"].value("c2_stream",false),"dual must fall back before allocation"); + const bool bounded=plan.is_object() && !plan["footprint"]["bounded_read"].is_null(); + if(c.name=="single-skip-exists")need(!stream && !bounded && c2_allocations==0,"existing output decoded"); + else need(c2_allocations==1 && (stream!=bounded),"expected one admitted row allocation"); + if(c.count==2)need(bounded && !stream,"dual must use the bounded reader"); #ifdef THUMBGEN_EXPECT_C2 if(c.count==1 && c.name!="single-skip-exists")need(stream && c2_allocations==1,"single did not exercise C2"); #else - need(!stream && c2_allocations==0,"reference unexpectedly streamed"); + need(!stream,"opt-in stream processing enabled"); #endif - if(c.name=="dual-first-oom" || c.name=="dual-first-null")need(result["status"]=="partial" && result["outputs"][1]["status"]=="success",result.dump()); - if(c.name=="dual-second-oom" || c.name=="dual-second-null")need(result["status"]=="partial" && result["outputs"][0]["status"]=="success",result.dump()); + if(c.name=="dual-first-oom" || c.name=="dual-first-null" || c.name=="dual-first-sampler-null" || c.name=="dual-first-resize") + need(result["status"]=="partial" && result["outputs"][1]["status"]=="success",result.dump()); + if(c.name=="dual-second-oom" || c.name=="dual-second-null" || c.name=="dual-second-sampler-null" || c.name=="dual-second-resize") + need(result["status"]=="partial" && result["outputs"][0]["status"]=="success",result.dump()); if(c.late_read)need(result["error"]["code"]=="decode_failed" && result["error"]["stage"]=="decode" && result["outputs"].empty(),result.dump()); if(c.phase=="invariant")need(result["error"]["code"]=="conversion_failed" && result["error"]["stage"]=="decode" && result["outputs"].empty(),"invariant error masked by output policy: "+result.dump()); Json files=Json::array();for(const auto& o:job.outputs)files.push_back(fs::exists(fs::u8path(o.path))?Json(o.path):Json(nullptr)); diff --git a/tests/test_png_tiff_rows.cpp b/tests/test_png_tiff_rows.cpp new file mode 100644 index 0000000..eaea24a --- /dev/null +++ b/tests/test_png_tiff_rows.cpp @@ -0,0 +1,145 @@ +#include "files.h" +#include "png_rows.h" +#include "tiff_rows.h" +#include +#include +#include + +namespace fs=std::filesystem; +using namespace thumbgen::detail; +namespace { +void require(bool condition,const char* message) { + if(!condition)throw std::runtime_error(message); +} + +struct Temp { + fs::path path=fs::temp_directory_path()/ + ("thumbgen-png-tiff-"+std::to_string(std::chrono::steady_clock::now().time_since_epoch().count())); + Temp() {fs::create_directory(path);} + ~Temp() {std::error_code error;fs::remove_all(path,error);} +}; + +void write_png(const fs::path& path,int channels,OIIO::TypeDesc format,bool offset) { + OIIO::ImageSpec spec(67,53,channels,format); + if(offset){spec.x=5;spec.y=7;} + spec.attribute("oiio:UnassociatedAlpha",1); + auto file=OIIO::ImageOutput::create(path.u8string()); + require(file && file->open(path.u8string(),spec),"could not create PNG fixture"); + std::vector row(std::size_t(spec.scanline_bytes())); + for(int y=0;y(y*13+x*19); + require(file->write_scanline(y+spec.y,0,format,row.data()),"could not write PNG fixture row"); + } + require(file->close(),"could not finish PNG fixture"); +} + +void write_tiff(const fs::path& path,bool wide,bool tiled,int channels,int bits,int pages=1, + const char* description=nullptr) { +#ifdef _WIN32 + auto* handle=TIFFOpenW(path.c_str(),wide?"w8b":"wl"); +#else + auto* handle=TIFFOpen(path.c_str(),wide?"w8b":"wl"); +#endif + std::unique_ptr file(handle,TIFFClose); + require(bool(file),"could not create TIFF fixture"); + constexpr int width=67,height=53,tile=16,strip=7; + const auto pixel=std::size_t(channels)*(bits/8); + for(int page=0;page=3?PHOTOMETRIC_RGB:PHOTOMETRIC_MINISBLACK); + TIFFSetField(handle,TIFFTAG_PLANARCONFIG,PLANARCONFIG_CONTIG); + TIFFSetField(handle,TIFFTAG_COMPRESSION,wide?COMPRESSION_ADOBE_DEFLATE:COMPRESSION_LZW); + TIFFSetField(handle,TIFFTAG_PREDICTOR,PREDICTOR_HORIZONTAL); + if(description)TIFFSetField(handle,TIFFTAG_IMAGEDESCRIPTION,description); + if(channels==4 || channels==2) { + std::uint16_t extra=wide?EXTRASAMPLE_UNASSALPHA:EXTRASAMPLE_ASSOCALPHA; + TIFFSetField(handle,TIFFTAG_EXTRASAMPLES,1,&extra); + } + if(tiled) { + TIFFSetField(handle,TIFFTAG_TILEWIDTH,tile); + TIFFSetField(handle,TIFFTAG_TILELENGTH,tile); + std::vector block(tile*tile*pixel); + for(int y=0;y(x*5+y*7+i*17+page*31); + require(TIFFWriteTile(handle,block.data(),x,y,0,0)==tmsize_t(block.size()), + "could not write TIFF fixture tile"); + } + } else { + TIFFSetField(handle,TIFFTAG_ROWSPERSTRIP,strip); + std::vector row(width*pixel); + for(int y=0;y(y*11+i*19+page*31); + require(TIFFWriteScanline(handle,row.data(),y,0)==1,"could not write TIFF fixture row"); + } + } + require(TIFFWriteDirectory(handle)==1,"could not finish TIFF fixture directory"); + } +} + +void compare_rows(const fs::path& path,bool png,int part) { + OIIO::ImageSpec config; + config.attribute("oiio:UnassociatedAlpha",1); + auto input=OIIO::ImageInput::open(path.u8string(),&config); + require(bool(input),"could not open fixture"); + OIIO::ImageSpec spec; + require(input->seek_subimage(part,0,spec),"could not select fixture page"); + auto reference=OIIO::ImageInput::open(path.u8string(),&config); + std::vector expected(std::size_t(spec.image_bytes())); + require(reference && reference->read_image(part,0,0,spec.nchannels,spec.format,expected.data()), + "could not decode reference image"); + constexpr auto budget=64*bounded_mib; + const auto plan=png?plan_png_rows(path,*input,spec,budget).read:plan_tiff_rows(path,spec,part,budget).read; + require(bool(plan.open) && plan.pixel_bytes==spec.pixel_bytes(),"native fixture was not admitted"); + require(plan.retained_bytes0,"native fixture omitted codec scratch"); + auto rows=plan.open(); + std::vector actual(expected.size()); + for(int y=0;yread(y,std::min(y+11,spec.height),actual.data()+std::size_t(y)*spec.scanline_bytes()); + rows->finish(); + require(actual==expected,"native rows differ from complete decode"); + try { + rows->read(0,1,actual.data()); + throw std::runtime_error("native reader allowed rewind"); + } catch(const FileFailure& error) { + require(error.code=="decode_failed","native reader returned incorrect rewind error"); + } +} +} + +int main() {try { + Temp temp; + const auto png=temp.path/"source.png",tiff=temp.path/"source.tif"; + for(int channels:{1,2,3,4}) { + for(int bits:{8,16}) { + write_png(png,channels,bits==16?OIIO::TypeDesc::UINT16:OIIO::TypeDesc::UINT8,channels==4); + preflight_png_header(png,64*bounded_mib); + compare_rows(png,true,0); + for(bool big:{false,true}) + for(bool tiled:{false,true}) { + write_tiff(tiff,big,tiled,channels,bits,2); + preflight_tiff_header(tiff,64*bounded_mib); + compare_rows(tiff,false,0); + compare_rows(tiff,false,1); + } + } + } + const std::string description(2*bounded_mib,'m'); + write_tiff(tiff,true,false,3,8,1,description.c_str()); + try { + preflight_tiff_header(tiff,bounded_mib); + throw std::runtime_error("oversized TIFF directory was admitted"); + } catch(const FileFailure& error) { + require(error.code=="decode_limit_exceeded","TIFF metadata limit returned the wrong error"); + } + return 0; +} catch(const std::exception& error) { + std::cerr<