diff --git a/CMakeLists.txt b/CMakeLists.txt index acf7bf1..a12ccd4 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -1,5 +1,5 @@ cmake_minimum_required(VERSION 3.24) -project(ThumbGen VERSION 0.1.3 LANGUAGES CXX) +project(ThumbGen VERSION 0.1.4 LANGUAGES CXX) find_package(OpenImageIO 3.2 CONFIG REQUIRED) find_package(OpenColorIO 2.5 CONFIG REQUIRED) @@ -68,7 +68,7 @@ set_property(DIRECTORY APPEND PROPERTY CMAKE_CONFIGURE_DEPENDS "${CMAKE_CURRENT_ 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 +target_sources(thumbgen_core PRIVATE src/exr_rows.cpp src/png_rows.cpp src/tiff_rows.cpp src/psd_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) @@ -554,6 +554,10 @@ if(BUILD_TESTING) 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 $) + add_test(NAME public_bounded_psd COMMAND ${Python3_EXECUTABLE} + ${CMAKE_CURRENT_SOURCE_DIR}/tests/test_bounded_psd_cli.py --exe $ + --runtime-dir $) + set_tests_properties(public_bounded_psd PROPERTIES TIMEOUT 120 LABELS "protocol;colour;scheduler") 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} diff --git a/README.en.md b/README.en.md index 08a5e2f..8dad823 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.3` · [Apache-2.0](LICENSE) +`0.1.4` · [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. 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. +Read OpenEXR, PNG, JPEG, TIFF, WebP, TGA, BMP, Radiance HDR, DPX and supported PSD composites. 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 5e90d69..d6bb35b 100644 --- a/README.md +++ b/README.md @@ -8,7 +8,7 @@ ThumbGen 为普通图片和复杂 EXR 快速生成缩略图。一次解码输出 为制作管线提供快速、懂 EXR 的预览能力。 -`0.1.3` · [Apache-2.0](LICENSE) +`0.1.4` · [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/large-previews.md)。可用 `thumbgen capabilities --json` 查看当前程序的格式支持。 +可读取 OpenEXR、PNG、JPEG、TIFF、WebP、TGA、BMP、Radiance HDR、DPX 和受支持的 PSD 合成图,输出 JPEG、PNG 和有损 WebP。支持有界解码的布局与预算设置见[大图预览](docs/large-previews.md)。可用 `thumbgen capabilities --json` 查看当前程序的格式支持。 ## 快速开始 diff --git a/docs/color-cms.md b/docs/color-cms.md index 6042347..7e4ed16 100644 --- a/docs/color-cms.md +++ b/docs/color-cms.md @@ -18,6 +18,8 @@ thumbgen convert frame.exr --output preview.jpg --ocio-config config.ocio --inpu 受支持的单张 PNG、JPEG、TIFF、WebP 会自动应用 RGB 或灰度 ICC。自动选择输入空间且未指定配置、显示器或视图时,这类文件使用 `ocio://default`,不受 `OCIO` 环境变量影响。显式选择配置或显示器与视图时,遵循上文的项目配置规则。显式指定输入空间会覆盖嵌入配置。 +受支持的 PSD v1 RGB 合成图也会自动应用其嵌入的 RGB ICC,并采用同样的配置优先级。含图层的 PSD 的存储合成图按单张图处理。自动使用的 ICC 超限、损坏或色彩模型不兼容时会报告错误。 + 用于 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/color-cms.md b/docs/en/color-cms.md index 19bf227..d88133c 100644 --- a/docs/en/color-cms.md +++ b/docs/en/color-cms.md @@ -18,6 +18,8 @@ Input space comes from `--input-space` first, otherwise file metadata. With no s 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. +Supported PSD v1 RGB composites automatically use embedded RGB ICC profiles and follow the same configuration precedence. The stored composite counts as one image even when the PSD contains layers. An embedded profile selected automatically produces an error if it exceeds the profile limit, is damaged, or uses an incompatible color model. + 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 dfe5676..1046aed 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.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. +Download the matching `thumbgen-0.1.4-*.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 is the same on both platforms and across versions, so you can use it directly after extraction. 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.3-linux-x86_64-glibc217.tar.gz -C "$HOME/.local/opt" +tar -xzf thumbgen-0.1.4-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 index c26a6ad..7914095 100644 --- a/docs/en/large-previews.md +++ b/docs/en/large-previews.md @@ -19,6 +19,9 @@ The balanced preset can decode eligible sources once for up to two preview sizes | 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. | +| PSD | Stored 8- or 16-bit RGB composites in PSD v1, with optional merged transparency. Supports Raw, PackBits RLE, ZIP and ZIP with prediction. | + +PSD previews read the composite saved in the file. Other presets and custom color settings use the same decoder for supported composites through a budget-checked full-image path. 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. diff --git a/docs/en/selection.md b/docs/en/selection.md index 36c04d3..b51d59f 100644 --- a/docs/en/selection.md +++ b/docs/en/selection.md @@ -22,6 +22,8 @@ thumbgen convert multipart.exr --output preview.jpg --part-name beauty 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. +For supported PSD v1 files, automatic color selection uses the stored composite when you omit both part and channel group. You can also select the composite directly with `--part 0` and optionally specify a channel group. For Raw and RLE files, `inspect` still lists available layers and you can select one explicitly by index or name. For ZIP and ZIP with prediction, `inspect` shows the supported composite only. + ## 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 010a106..c785157 100644 --- a/docs/installation.md +++ b/docs/installation.md @@ -4,7 +4,7 @@ 使用适合平台的完整 ThumbGen 程序目录。Windows 需要保留随附 DLL;Linux 需要保留 bin/lib 相对位置和执行权限。不要只复制单个可执行文件。 -下载匹配平台的 `thumbgen-0.1.3-*.zip` 或 `.tar.gz`,先核对随附的 `SHA256SUMS`。两个压缩包都只有固定的 `ThumbGen/` 外层目录,里面直接是 `bin/`、`share/`、`licenses/`,Linux 另有 `lib/`;目录名不含版本或平台,无需解压后改名或移动。 +下载匹配平台的 `thumbgen-0.1.4-*.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.3-linux-x86_64-glibc217.tar.gz -C "$HOME/.local/opt" +tar -xzf thumbgen-0.1.4-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 index 523a670..7f1c4ac 100644 --- a/docs/large-previews.md +++ b/docs/large-previews.md @@ -19,6 +19,9 @@ thumbgen convert renders/frame.exr --output-dir previews --size 960x960 --size 4 | BMP | 无压缩的 24 位 RGB 和 32 位 RGB(A)。 | | TGA | 无压缩、非交错的 24 位 RGB 和 32 位 RGBA。解码器保留完整原生帧。 | | WebP | 有损静态 RGB/RGBA。解码器保留压缩输入和原生帧。无损和动画可在满足解码限制时使用整图路径。 | +| PSD | PSD v1 的 8 位、16 位 RGB 合成图,可含合并透明度。支持 Raw、PackBits RLE、ZIP 和带预测的 ZIP。 | + +PSD 预览读取文件中保存的合成图。使用其他预设或自定义色彩设置时,仍可通过同一解码器处理受支持的合成图,整图路径也会检查解码预算。 有界布局每边最多 65,536 像素,格式本身可能有更低的限制。EXR 的限制包括 8 MiB 元数据分配、最多 1,048,576 个偏移表条目和 64 MiB 解包块。缩放工作缓冲区也有上限。其他布局、预设、更多输出尺寸以及数据或 Deep 预览,在满足对应限制时沿用现有处理路径。输入校验失败或超出计划限制时,该任务会在写出预览前报告错误。 diff --git a/docs/selection.md b/docs/selection.md index 709f5c7..c147fa4 100644 --- a/docs/selection.md +++ b/docs/selection.md @@ -22,6 +22,8 @@ thumbgen convert multipart.exr --output preview.jpg --part-name beauty `--visualize auto` 使用默认选择策略时,如果其他 part 的候选都是阴影或环境光遮蔽等已识别的辅助 AOV,可选用唯一一组无前缀 RGB(A)。没有颜色候选时,此模式可跨 part 预览 Cryptomatte 家族。多个家族中唯一的 `crypto_object` 或 `CryptoObject` 优先,名称不区分大小写。其他歧义需显式指定 part、通道组或 Cryptomatte 家族。 +受支持的 PSD v1 文件在未指定 part 或通道组、自动选择颜色图像时使用存储的合成图。也可使用 `--part 0` 直接选择合成图,按需附加通道组。Raw 和 RLE 文件的 `inspect` 仍会列出可用图层,可按索引或名称显式选择。ZIP 和带预测的 ZIP 文件的 `inspect` 仅显示受支持的合成图。 + ## 连续帧保持一致 在批处理任务中使用相同的 `sequence_id`,即可固定同一组图层与通道。后续帧缺失或改变通道时报告错误,而不会悄悄选择另一张图。 diff --git a/scripts/linux/stage-validation.py b/scripts/linux/stage-validation.py index 78cb196..794182e 100644 --- a/scripts/linux/stage-validation.py +++ b/scripts/linux/stage-validation.py @@ -56,6 +56,8 @@ python_tests.append('test_cryptomatte_cli.py') if any(test['name'] == 'public_sampled_id' for test in suite['tests']): python_tests.append('test_sampled_id_cli.py') +if any(test['name'] == 'public_bounded_psd' for test in suite['tests']): + python_tests.extend(('psd_fixtures.py', 'test_bounded_psd_cli.py')) for name in (*python_tests, 'requirements.txt'): shutil.copy2(repo / 'tests' / name, stage / 'tests' / name) for path in (repo / 'schemas').glob('*.json'): @@ -69,6 +71,7 @@ str(repo / 'tests/test_aov_cli.py'): '@TESTS@/test_aov_cli.py', str(repo / 'tests/test_cryptomatte_cli.py'): '@TESTS@/test_cryptomatte_cli.py', str(repo / 'tests/test_sampled_id_cli.py'): '@TESTS@/test_sampled_id_cli.py', + str(repo / 'tests/test_bounded_psd_cli.py'): '@TESTS@/test_bounded_psd_cli.py', str(repo / 'schemas'): '@SCHEMAS@', str(cache / 'sdk/lib'): '@LIB@', str(tools_cache / 'tools/python-3.11.11/bin/python3'): '@PYTHON@'}) diff --git a/src/core.cpp b/src/core.cpp index a27135d..b677e68 100644 --- a/src/core.cpp +++ b/src/core.cpp @@ -12,6 +12,7 @@ #include "png_rows.h" #include "tiff_rows.h" #include "other_rows.h" +#include "psd_rows.h" #ifdef THUMBGEN_C2_PNG_STREAM #include "c2_memory.h" #include "c2_png_metadata.h" @@ -153,6 +154,10 @@ static Json spec_json(const OIIO::ImageSpec& s, int part) { {"display_window",{s.full_x,s.full_y,s.full_width,s.full_height}}, {"colour_space",s.get_string_attribute("oiio:ColorSpace")}}; } +static const char* psd_compression_name(unsigned compression) { + static constexpr const char* names[]={"raw","rle","zip","zip_prediction"}; + return names[compression]; +} static Json candidates_json(const OIIO::ImageSpec& spec,int part) { Json result=Json::array(); for(const auto& candidate:detail::classify(spec))result.push_back(detail::candidate_json(spec,candidate,part)); @@ -332,11 +337,19 @@ Json Engine::inspect(const std::string& input) { 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; + std::optional psd; + if(!jpeg && !ec) { + psd=detail::probe_psd_rows(input,bytes,unlimited,std::numeric_limits::max(),false); + if(!psd) + other=detail::probe_other_rows(input,bytes,unlimited,OIIO::ImageSpec{},std::numeric_limits::max()); + } + // Raw and RLE still expose their layers through the plugin. ZIP + // composite metadata is available without opening an OIIO decoder. + const auto* spec=jpeg?&jpeg->spec:psd && psd->compression>=2?&psd->spec: + other && other->spec?&*other->spec:nullptr; if(spec) { auto part=spec_json(*spec,0); + if(psd)part["compression"]=psd_compression_name(psd->compression); part["candidates"]=candidates_json(*spec,0); result["parts"]=Json::array({std::move(part)});result["ok"]=true; return result; @@ -422,21 +435,26 @@ Json Engine::convert(const Job& job) { bool container_icc=false; std::optional jpeg; std::optional other; + std::optional psd; std::string probed_format; try { + const bool auto_input=!data && job.options.input_space=="auto"; + const auto limit=auto_input?detail::icc_profile_limit:std::numeric_limits::max(); + const bool psd_composite=!data && job.options.part_name.empty() && + (job.options.part==0 || (job.options.part<0 && job.options.channels.empty())); // 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)); + 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(psd_composite && + (psd=detail::probe_psd_rows(job.input,stamp.size,decode_budget,limit,auto_input))) + probed_format="psd"; + else if((other=detail::probe_other_rows(job.input,stamp.size,decode_budget,read_config,limit))) + probed_format=other->format; + container_icc=!data && (psd?psd->has_icc:jpeg?jpeg->has_icc:detail::container_has_icc(job.input,limit)); } catch(const detail::CmsFailure& error){throw Failure("colour_input_unsupported",error.what());} OIIO::ImageInput::unique_ptr in; @@ -453,14 +471,26 @@ Json Engine::convert(const Job& job) { 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(); + std::optional psd_profile; + if(psd) { + // Selection snapshots copy their ImageSpecs. Keep the PSD + // profile out of those snapshots and transfer it after selection. + auto& attributes=psd->spec.extra_attribs; + auto profile=attributes.find(OIIO::string_view("ICCProfile")); + if(profile!=attributes.end()) { + psd_profile.emplace(std::move(*profile)); + attributes.erase(profile); + } + } + const auto* deferred_spec=psd?&psd->spec:jpeg?&jpeg->spec:deferred_other?&*other->spec:nullptr; + if(!deferred_spec)open_input(); + const std::string input_format=deferred_spec?probed_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(input_format=="openexr"); #endif - if(!data && detail::container_separated_colour(job.input)) + if(!data && !psd && detail::container_separated_colour(job.input)) throw Failure("colour_input_unsupported","CMYK/separated input requires an external profile-aware conversion to RGB"); stage="selection"; OIIO::ImageSpec spec; @@ -492,9 +522,9 @@ Json Engine::convert(const Job& job) { } for(int p=0;;++p) { OIIO::ImageSpec scanned; - if(jpeg || deferred_other) { + if(deferred_spec) { if(p!=0)break; - scanned=jpeg?jpeg->spec:*other->spec; + scanned=*deferred_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"))) @@ -632,6 +662,7 @@ Json Engine::convert(const Job& job) { r["selection"]["lock_status"]="created";r["selection"]["locked"]=chosen_key; } r["source"]=spec_json(spec,part); + if(psd)r["source"]["compression"]=psd_compression_name(psd->compression); if(deep)r["deep"]={{"mode","flatten"},{"policy","deep-colour-sweep-v1"},{"mapping",deep->identity()}, {"sample_limit",job.options.deep_samples_per_pixel},{"buffer_limit_bytes",job.options.max_decode_mib*1024ULL*1024ULL}, {"samples",0},{"chunks",0},{"peak_buffer_bytes",0}}; @@ -641,6 +672,7 @@ Json Engine::convert(const Job& job) { // unselected candidates before admission and never propagate a source // profile onto the CMS/OCIO-converted RGB pixels. all_choices.clear();choices.clear(); + if(psd_profile)spec.extra_attribs.push_back(std::move(*psd_profile)); bool all_skip=!job.outputs.empty(); for(const auto& output:job.outputs) { if(output.existing!="skip"){all_skip=false;break;} @@ -662,7 +694,7 @@ Json Engine::convert(const Job& job) { raw_cmyk.erase_attribute("ICCProfile"); input_plan=detail::channel_plan(raw_cmyk,{0,1,2,3},false); } - const bool icc_format=input_format=="png" || input_format=="jpeg" || input_format=="tiff" || input_format=="webp"; + const bool icc_format=psd || input_format=="png" || input_format=="jpeg" || input_format=="tiff" || input_format=="webp"; 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); @@ -739,6 +771,11 @@ Json Engine::convert(const Job& job) { (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; + if(psd) { + source_codec_bytes=detail::checked_bytes_add(psd->read.retained_bytes,psd->read.codec_bytes); + source_codec_bytes=detail::checked_bytes_add(source_codec_bytes, + detail::checked_bytes_mul(spec.width,psd->read.pixel_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 @@ -779,6 +816,7 @@ Json Engine::convert(const Job& job) { 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; + else if(psd && rgb && colour_plan.bounded_options)candidate=&psd->read; } c2_sizes.clear(); if(candidate && candidate->open) { @@ -805,8 +843,11 @@ Json Engine::convert(const Job& job) { // 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)): + auto pixel_bytes=integer_linear?channels.size()*(colour_plan.sample_bytes+2*sizeof(float)): fast_srgb?channels.size():input_plan.pixel_bytes; + // PSD's reference route holds the float raster and its packed + // colour copy. Reorientation may briefly retain a third raster. + if(psd)pixel_bytes*=orientation==1?2:3; 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) @@ -1232,11 +1273,26 @@ Json Engine::convert(const Job& job) { in->close(); try{detail::read_cmyk_jpeg(job.input,spec.width,spec.height,colour_pixels);read_ok=true;} catch(const detail::CmsFailure& error){throw Failure("colour_input_unsupported",error.what());} + } else if(psd) { + try { + const auto native=psd->read.open(); + const auto row_samples=spec.width*spec.nchannels; + std::vector row(std::size_t(spec.width)*psd->read.pixel_bytes); + for(int y=0;yread(y,y+1,row.data()); + if(!OIIO::convert_pixel_values(spec.format,row.data(),OIIO::TypeDesc::FLOAT, + colour_pixels+std::size_t(y)*row_samples,row_samples)) + throw Failure("decode_failed","cannot convert native PSD row to float"); + } + native->finish(); + read_ok=true; + } catch(...) {verify_source();throw;} } else read_ok=detail::read_selected(*in,cmyk?raw_cmyk:spec,part,input_plan,false,colour_pixels); TG_EXR_TOCK(read_tick,"exr_read_selected_ms"); const std::string read_error=read_ok?std::string{}:in->geterror(); TG_EXR_TICK(close_tick); - in->close(); + if(in)in->close(); TG_EXR_TOCK(close_tick,"exr_input_close_ms"); if(impl_->observer)impl_->observer("decoded",job); verify_source(); diff --git a/src/psd_rows.cpp b/src/psd_rows.cpp new file mode 100644 index 0000000..19d7fcd --- /dev/null +++ b/src/psd_rows.cpp @@ -0,0 +1,568 @@ +#include "psd_rows.h" +#include "cms_input.h" +#include "files.h" +#include +#include +#include +#include +#include +#include + +namespace thumbgen::detail { +namespace { +using Byte=unsigned char; +using Offset=std::uint64_t; +constexpr unsigned max_dimension=30000; +constexpr unsigned max_channels=56; +constexpr std::size_t metadata_limit=4*bounded_mib; +constexpr std::size_t zip_chunk=32*1024; +constexpr std::size_t inflate_bytes=64*1024; +constexpr std::size_t rle_entries=256; + +enum Compression : unsigned { raw=0, rle=1, zip=2, predicted_zip=3 }; + +void require(bool valid,const char* code,const char* message) { + if(!valid)throw FileFailure(code,message); +} + +void admit(Offset bytes,Offset budget,const char* message) { + require(bytes<=budget,"decode_limit_exceeded",message); +} + +unsigned be16(const Byte* data) { + return (unsigned(data[0])<<8)|data[1]; +} + +std::uint32_t be32(const Byte* data) { + return (std::uint32_t(be16(data))<<16)|be16(data+2); +} + +struct Section { + Offset offset=0,size=0; + Offset end() const {return offset+size;} +}; + +class Source { +public: + Source(const std::string& path,Offset size,const char* error) + :file_(std::filesystem::u8path(path),std::ios::binary),size_(size),error_(error) {} + + bool opened() const {return file_.is_open();} + Offset size() const {return size_;} + void read(Offset offset,void* out,std::size_t bytes) { + require(offset<=size_ && bytes<=size_-offset && + offset<=Offset(std::numeric_limits::max()), + error_,"PSD read exceeds source range"); + if(position_!=offset)file_.seekg(static_cast(offset)); + require(bool(file_.read(static_cast(out),static_cast(bytes))), + error_,"could not read PSD source"); + position_=offset+bytes; + } + +private: + std::ifstream file_; + Offset size_,position_=0; + const char* error_; +}; + +class Cursor { +public: + Cursor(Source& source,Section section):source_(source),position_(section.offset),end_(section.end()) {} + Offset remaining() const {return end_-position_;} + + Section take(Offset bytes) { + require(bytes<=remaining(),"open_failed","PSD block exceeds enclosing section"); + const Section section{position_,bytes}; + position_+=bytes; + return section; + } + + template std::array read() { + std::array bytes; + source_.read(take(N).offset,bytes.data(),N); + return bytes; + } + + Section sized_section() {return take(be32(read<4>().data()));} + +private: + Source& source_; + Offset position_,end_; +}; + +struct Resources { + Section background,icc,exif1,exif3; + bool missing_composite=false; +}; + +Resources resources(Source& source,Section section) { + Resources result; + Cursor blocks(source,section); + while(blocks.remaining()) { + const auto header=blocks.read<7>(); + require(std::memcmp(header.data(),"8BIM",4)==0,"open_failed","invalid PSD image resource signature"); + // The Pascal length byte is already consumed. The whole name is even-aligned. + const unsigned name_length=header[6]; + blocks.take(name_length+((name_length+1)&1)); + const auto payload=blocks.sized_section(); + blocks.take(payload.size&1); + switch(be16(header.data()+4)) { + case 1010: if(!result.background.offset)result.background=payload; break; + case 1039: if(!result.icc.offset)result.icc=payload; break; + case 1057: { + Cursor version(source,payload); + const auto info=version.read<5>(); + require(info[4]<=1,"open_failed","invalid PSD merged image flag"); + result.missing_composite|=info[4]==0; + break; + } + case 1058: if(!result.exif1.offset)result.exif1=payload; break; + case 1059: if(!result.exif3.offset)result.exif3=payload; break; + } + } + return result; +} + +bool negative_layer_count(Source& source,Section section) { + Cursor layers(source,section); + const auto count=be16(layers.read<2>().data()); + require(count!=0x8000,"open_failed","invalid PSD layer count"); + return (count&0x8000)!=0; +} + +bool merged_alpha(Source& source,Section section,unsigned sample_bytes) { + if(!section.size)return false; + Cursor masks(source,section); + const auto layers=masks.sized_section(); + bool alpha=layers.size && negative_layer_count(source,layers); + if(!masks.remaining())return alpha; // Some writers omit the empty global mask section. + masks.sized_section(); // Global layer mask data. + bool have_layers=layers.size!=0; + while(masks.remaining()>=12) { + const auto tag=masks.read<8>(); + require(std::memcmp(tag.data(),"8BIM",4)==0 || std::memcmp(tag.data(),"8B64",4)==0, + "open_failed","invalid PSD additional layer info signature"); + const auto payload=masks.sized_section(); + const char* layer_key=sample_bytes==2?"Lr16":"Layr"; + if(std::memcmp(tag.data()+4,layer_key,4)==0) { + require(!have_layers,"open_failed","duplicate PSD layer info"); + alpha=negative_layer_count(source,payload); + have_layers=true; + } + // PSD global tagged blocks are commonly padded to a multiple of four. + // The enclosing section may end directly after the final payload. + if(masks.remaining())masks.take((4-(payload.size&3))&3); + } + require(masks.remaining()<=3,"open_failed","truncated PSD additional layer info header"); + while(masks.remaining()) + require(masks.read<1>()[0]==0,"open_failed","invalid PSD layer info padding"); + return alpha; +} + +int exif_orientation(Source& source,Section exif) { + if(exif.size<8)return 0; + std::array header; + source.read(exif.offset,header.data(),header.size()); + if(std::memcmp(header.data(),"Exif\0\0",6)==0 && exif.size>=14) { + exif.offset+=6; + exif.size-=6; + source.read(exif.offset,header.data(),header.size()); + } + const bool little=header[0]=='I' && header[1]=='I'; + if(!little && !(header[0]=='M' && header[1]=='M'))return 0; + const auto u16=[little](const Byte* bytes) {return little?unsigned(bytes[0])|(unsigned(bytes[1])<<8):be16(bytes);}; + const auto u32=[little,u16](const Byte* bytes) { + return little?std::uint32_t(u16(bytes))|(std::uint32_t(u16(bytes+2))<<16):be32(bytes); + }; + const Offset ifd=u32(header.data()+4); + if(u16(header.data()+2)!=42 || ifd<8 || ifd>exif.size-2)return 0; + Cursor entries(source,{exif.offset+ifd,exif.size-ifd}); + const auto count=u16(entries.read<2>().data()); + if(Offset(count)*12+4>entries.remaining())return 0; + for(unsigned i=0;i(); + if(u16(entry.data())!=274 || u16(entry.data()+2)!=3 || u32(entry.data()+4)!=1)continue; + const auto orientation=u16(entry.data()+8); + if(orientation>=1 && orientation<=8)return int(orientation); + } + return 0; +} + +void add_orientation(Source& source,const Resources& metadata,OIIO::ImageSpec& spec) { + // The locked OIIO XMP decoder treats tiff:Orientation as redundant. + int orientation=exif_orientation(source,metadata.exif3); + if(!orientation)orientation=exif_orientation(source,metadata.exif1); + if(orientation)spec.attribute("Orientation",orientation); +} + +struct Layout { + Offset size=0,payload=0; + unsigned width=0,height=0,sample_bytes=0,planes=0,channels=0,compression=0; + std::array background{1.0f,1.0f,1.0f}; + + unsigned row_bytes() const {return width*sample_bytes;} + Offset plane_bytes() const {return Offset(row_bytes())*height;} + Offset rle_table_bytes() const {return Offset(height)*planes*2;} +}; + +void unpack_row(const Byte* packed,std::size_t length,Byte* row,std::size_t row_bytes) { + std::size_t in=0,out=0; + while(in slab; + for(unsigned plane=0;plane(rle_entries,layout.height-y); + read_lengths(plane,y,slab.data(),count); + for(unsigned row=0;row(rle_entries,layout_.height-y); + read_lengths(plane,y,slab.data(),count); + } + const auto count=be16(slab.data()+2*(y%rle_entries)); + auto& offset=positions_[plane]; + require(count && count<=ends_[plane]-offset,"decode_failed","PSD PackBits row crosses plane boundary"); + source_.read(offset,packed_.data(),count); + unpack_row(packed_.data(),count,row,layout_.row_bytes()); + offset+=count; + if(y+1==layout_.height) + require(offset==ends_[plane],"decode_failed","PSD PackBits plane length changed during read"); + } + +private: + void read_lengths(unsigned plane,unsigned y,Byte* slab,unsigned count) { + source_.read(layout_.payload+2*(Offset(plane)*layout_.height+y),slab,2*count); + } + Source& source_; + const Layout& layout_; + std::vector packed_; + std::array positions_{},ends_{}; + std::array,5> lengths_{}; +}; + +struct InflateMemory { + Offset live=0,limit=0; + + struct alignas(std::max_align_t) Allocation {Offset size;}; + + static voidpf allocate(voidpf context,uInt count,uInt size) { + auto& memory=*static_cast(context); + const Offset bytes=Offset(count)*size; + if(bytes>memory.limit-memory.live || sizeof(Allocation)>memory.limit-memory.live-bytes)return nullptr; + const Offset cost=bytes+sizeof(Allocation); + auto* block=static_cast(std::malloc(static_cast(cost))); + if(!block)return nullptr; + ::new (block) Allocation{cost}; + memory.live+=cost; + return block+1; + } + + static void release(voidpf context,voidpf address) { + if(!address)return; + auto* block=static_cast(address)-1; + static_cast(context)->live-=block->size; + std::free(block); + } +}; + +class Inflater { +public: + Inflater()=default; + Inflater(const Inflater&)=delete; + Inflater& operator=(const Inflater&)=delete; + ~Inflater() {if(active_)inflateEnd(&stream_);} + + void start(Offset offset,InflateMemory& memory) { + stream_.zalloc=InflateMemory::allocate; + stream_.zfree=InflateMemory::release; + stream_.opaque=&memory; + check(inflateInit(&stream_)); + active_=true; + next_offset_=offset; + } + + void resume(Inflater& earlier) { + require(!earlier.ended_,"decode_failed","PSD ZIP output ends before all planes"); + check(inflateCopy(&stream_,&earlier.stream_)); + active_=true; + // The copied bit accumulator and history belong to this inflater. Feed + // its unread bytes from the file so it never references another buffer. + next_offset_=earlier.next_offset_-earlier.stream_.avail_in; + stream_.next_in=nullptr; + stream_.avail_in=0; + stream_.next_out=nullptr; + stream_.avail_out=0; + } + + void read(Source& source,Byte* destination,unsigned count) { + stream_.next_out=destination; + stream_.avail_out=count; + while(stream_.avail_out && !ended_)step(source); + require(stream_.avail_out==0,"decode_failed","PSD ZIP output is shorter than its composite layout"); + } + + void skip(Source& source,Byte* scratch,unsigned capacity,Offset count) { + while(count) { + const auto chunk=static_cast(std::min(capacity,count)); + read(source,scratch,chunk); + count-=chunk; + } + } + + void finish(Source& source) { + Byte extra; + stream_.next_out=&extra; + stream_.avail_out=1; + while(!ended_ && stream_.avail_out)step(source); + require(ended_ && stream_.avail_out==1,"decode_failed","PSD ZIP output is longer than its composite layout"); + require(next_offset_-stream_.avail_in==source.size(),"decode_failed","unexpected bytes after PSD ZIP composite"); + } + +private: + static void check(int code) { + require(code!=Z_MEM_ERROR,"decode_limit_exceeded","could not allocate PSD ZIP decoder"); + require(code==Z_OK || code==Z_STREAM_END,"decode_failed","invalid or truncated PSD ZIP stream"); + } + + void step(Source& source) { + if(!stream_.avail_in && next_offset_(std::min(input_.size(),source.size()-next_offset_)); + source.read(next_offset_,input_.data(),chunk); + next_offset_+=chunk; + stream_.next_in=input_.data(); + stream_.avail_in=chunk; + } + const auto in=stream_.avail_in,out=stream_.avail_out; + const int code=inflate(&stream_,Z_NO_FLUSH); + check(code); + ended_=code==Z_STREAM_END; + require(ended_ || in!=stream_.avail_in || out!=stream_.avail_out, + "decode_failed","incomplete PSD ZIP stream"); + } + + z_stream stream_{}; + std::array input_; + Offset next_offset_=0; + bool active_=false,ended_=false; +}; + +template +Sample remove_background(Sample composite,Sample coverage,float background) { + // Match OIIO's native integer straight-alpha quantization for a valid matte. + // Clamp inconsistent matte samples before converting to the unsigned type. + constexpr float maximum=std::numeric_limits::max(); + constexpr float scale=1.0f/maximum; + const float alpha=coverage*scale; + if(alpha==0.0f)return 0; + const float straight=(composite-((1.0f-alpha)*background)/scale)/alpha; + return static_cast(std::clamp(straight,0.0f,maximum)); +} + +class PsdRows final : public NativeRowSource { +public: + PsdRows(const std::string& path,const Layout& layout) + :layout_(layout),source_(path,layout.size,"decode_failed"), + plane_row_(layout.compression>=zip?std::max(zip_chunk,layout.row_bytes()):layout.row_bytes()), + zip_memory_{0,layout.channels*inflate_bytes} { + require(source_.opened(),"decode_failed","could not reopen PSD source"); + if(layout_.compression==rle)rle_=std::make_unique(source_,layout_); + if(layout_.compression>=zip) { + zip_=std::make_unique(layout_.channels); + zip_[0].start(layout_.payload,zip_memory_); + for(unsigned plane=1;plane=0 && first(destination); + while(next_row_(out); + else read_row(out); + out+=layout_.row_bytes()*layout_.channels; + ++next_row_; + } + } + + void finish() override { + require(next_row_==layout_.height,"decode_failed","incomplete PSD composite row read"); + if(finished_)return; + if(zip_) { + auto& last=zip_[layout_.channels-1]; + last.skip(source_,plane_row_.data(),unsigned(plane_row_.size()), + layout_.plane_bytes()*(layout_.planes-layout_.channels)); + last.finish(source_); + } + if(rle_) { + for(unsigned plane=layout_.channels;planeread(plane,y,plane_row_.data()); + } + finished_=true; + } + +private: + void read_plane(unsigned plane) { + if(zip_)zip_[plane].read(source_,plane_row_.data(),layout_.row_bytes()); + else if(rle_)rle_->read(plane,next_row_,plane_row_.data()); + else source_.read(layout_.payload+plane*layout_.plane_bytes()+Offset(next_row_)*layout_.row_bytes(), + plane_row_.data(),layout_.row_bytes()); + } + + template + void read_row(Byte* out) { + // Decode alpha first so RGB can be corrected directly in the caller's + // row without allocating a second interleaved or planar buffer. + for(unsigned i=layout_.channels;i>0;--i) { + const unsigned channel=i-1; + read_plane(channel); + Sample previous=0; + for(unsigned x=0;x(be16(bytes)); + if(layout_.compression==predicted_zip) { + value=static_cast(value+previous); + previous=value; + } + auto* pixel=out+x*layout_.channels*sizeof(Sample); + if(layout_.channels==4 && channel<3) { + Sample alpha; + std::memcpy(&alpha,pixel+3*sizeof(Sample),sizeof(Sample)); + value=remove_background(value,alpha,layout_.background[channel]); + } + std::memcpy(pixel+channel*sizeof(Sample),&value,sizeof(Sample)); + } + } + } + + Layout layout_; + Source source_; + std::vector plane_row_; + InflateMemory zip_memory_; + std::unique_ptr zip_; + std::unique_ptr rle_; + unsigned next_row_=0; + bool finished_=false; +}; +} + +std::optional probe_psd_rows(const std::string& input,Offset source_size, + Offset decode_budget,std::size_t icc_limit,bool load_icc) { + Source source(input,source_size,"open_failed"); + if(!source.opened() || source_size<4)return std::nullopt; + Cursor file(source,{0,source_size}); + const auto signature=file.read<4>(); + if(std::memcmp(signature.data(),"8BPS",4)!=0)return std::nullopt; + if(be16(file.read<2>().data())!=1)return std::nullopt; + const auto header=file.read<20>(); + const auto depth=be16(header.data()+16),mode=be16(header.data()+18); + if(mode!=3 || (depth!=8 && depth!=16))return std::nullopt; + require(std::all_of(header.begin(),header.begin()+6,[](Byte value){return value==0;}), + "open_failed","invalid PSD reserved header fields"); + + Layout layout; + layout.size=source_size; + layout.height=be32(header.data()+8); + layout.width=be32(header.data()+12); + layout.planes=be16(header.data()+6); + layout.sample_bytes=depth/8; + require(layout.width && layout.height && layout.width<=max_dimension && layout.height<=max_dimension, + "invalid_dimensions","invalid PSD dimensions"); + require(layout.planes>=3 && layout.planes<=max_channels,"open_failed","invalid PSD RGB channel count"); + require(!file.sized_section().size,"open_failed","unexpected PSD RGB color mode data"); + const auto resource_section=file.sized_section(); + const auto layer_section=file.sized_section(); + const auto metadata=resources(source,resource_section); + require(!metadata.missing_composite && file.remaining()>=2, + "decode_failed","PSD does not contain a valid merged image"); + layout.compression=be16(file.read<2>().data()); + if(layout.compression>predicted_zip)return std::nullopt; + layout.payload=source_size-file.remaining(); + require(file.remaining()>0,"decode_failed","PSD merged image is missing its pixel data"); + layout.channels=merged_alpha(source,layer_section,layout.sample_bytes)?4:3; + require(layout.channels<=layout.planes,"open_failed","PSD merged transparency channel is missing"); + switch(layout.compression) { + case raw: + require(file.remaining()==layout.plane_bytes()*layout.planes, + "decode_failed","PSD raw composite length does not match its layout"); + break; + case rle: + require(file.remaining()>layout.rle_table_bytes(),"decode_failed","truncated PSD PackBits table or payload"); + break; + } + if(layout.channels==4 && metadata.background.offset) { + Cursor background(source,metadata.background); + const auto bytes=background.read<5>(); + // Preserve the locked PSD plugin's interpretation of resource 1010, + // with white as the default when the resource is absent. + for(unsigned c=0;c<3;++c)layout.background[c]=bytes[4-c]*(1.0f/255.0f); + } + + // Include the planning copy and the ImageSpec copy used for selection/readback. + const Offset icc_bytes=load_icc?metadata.icc.size:0; + if(icc_bytes>std::min(icc_limit,metadata_limit))throw CmsFailure("PSD ICC resource exceeds profile limit"); + const auto retained=checked_bytes_add(2*icc_bytes,checked_bytes_add(input.size(),4096)); + // Include stream buffering, the reader object and temporary native path encoding. + Offset codec=checked_bytes_add(64*1024+sizeof(PsdRows)+layout.row_bytes(), + checked_bytes_mul(2,input.size())); + if(layout.compression==rle)codec+=sizeof(RleRows)+65535+2*rle_entries; + if(layout.compression>=zip)codec+=zip_chunk+layout.channels*(sizeof(Inflater)+inflate_bytes); + admit(checked_bytes_add(retained,codec),decode_budget,"PSD metadata and row decoder exceed decode budget"); + + PsdProbe result; + result.compression=layout.compression; + result.has_icc=metadata.icc.offset!=0; + auto& spec=result.spec; + spec=OIIO::ImageSpec(int(layout.width),int(layout.height),int(layout.channels), + depth==8?OIIO::TypeDesc::UINT8:OIIO::TypeDesc::UINT16); + if(layout.channels==4)spec.attribute("oiio:UnassociatedAlpha",1); + add_orientation(source,metadata,spec); + if(icc_bytes) { + std::vector profile(static_cast(icc_bytes)); + source.read(metadata.icc.offset,profile.data(),profile.size()); + spec.attribute("ICCProfile",OIIO::TypeDesc(OIIO::TypeDesc::UINT8,int(icc_bytes)),profile.data()); + } + result.read={layout.channels*layout.sample_bytes,retained,codec, + [input,layout]{return std::make_unique(input,layout);}}; + return result; +} +} diff --git a/src/psd_rows.h b/src/psd_rows.h new file mode 100644 index 0000000..7ffbd19 --- /dev/null +++ b/src/psd_rows.h @@ -0,0 +1,19 @@ +#pragma once + +#include "bounded_read.h" +#include +#include +#include + +namespace thumbgen::detail { +struct PsdProbe { + OIIO::ImageSpec spec; + NativeReadPlan read; + bool has_icc=false; + unsigned compression=0; +}; + +// Plans only the PSD v1 RGB composite. No layer records or pixels are decoded. +std::optional probe_psd_rows(const std::string& input,std::uint64_t source_size, + std::uint64_t decode_budget,std::size_t icc_limit,bool load_icc); +} diff --git a/tests/psd_fixtures.py b/tests/psd_fixtures.py new file mode 100644 index 0000000..b2ad40f --- /dev/null +++ b/tests/psd_fixtures.py @@ -0,0 +1,293 @@ +"""Synthetic PSD v1 fixtures and independent lossless image I/O for CLI tests.""" +import random +import struct +import zlib + + +RAW, RLE, ZIP, PREDICTED_ZIP = range(4) +WIDTH, HEIGHT = 259, 11 +LAYER_RGB = (19, 91, 217) + + +def padded(data, alignment): + return data + bytes(-len(data) % alignment) + + +def section(data): + return struct.pack(">I", len(data)) + data + + +def resource(number, data, name=b""): + return (struct.pack(">4sH", b"8BIM", number) + + padded(bytes((len(name),)) + name, 2) + padded(section(data), 2)) + + +def version_info(has_merged): + names = b"".join(struct.pack(">I", len(name)) + name.encode("utf-16-be") + for name in ("Fixture", "Fixture")) + return resource(1057, struct.pack(">IB", 1, has_merged) + names + struct.pack(">I", 1)) + + +def auxiliary_channel(spot): + # DisplayInfo v1, RGB swatch, 100% opacity, spot (2) or saved alpha (0). + return (resource(1006, b"\x04Spot" if spot else b"\x05Saved") + + resource(1077, struct.pack(">I6HB", 1, 0, 65535, 0, 0, 0, 100, 2 if spot else 0))) + + +def samples(values, depth, endian=">"): + return bytes(values) if depth == 8 else struct.pack(f"{endian}{len(values)}H", *values) + + +def layer_info(depth, count, tagged=False): + # A 2x2 layer with RGB distinct from the merged RGB detects layer/composite mixups. + channels = [b"\0\0" + samples([v * (257 if depth == 16 else 1)] * 4, depth) for v in LAYER_RGB] + record = struct.pack(">4iH", 0, 0, 2, 2, len(channels)) + record += b"".join(struct.pack(">hI", i, len(data)) for i, data in enumerate(channels)) + record += b"8BIMnorm\xff\0\0\0" + section(bytes(8) + padded(b"\x05Layer", 4)) + info = padded(struct.pack(">h", count) + record + b"".join(channels), 2) + if tagged: + return bytes(8) + b"8BIMLr16" + padded(section(info), 4) + return section(info) + bytes(4) + + +def prefix(width, height, depth, channels, resources=b"", layers=b""): + # Adobe Photoshop File Formats Specification, Image Data Section. + # https://www.adobe.com/devnet-apps/photoshop/fileformatashtml/ + # PSD fields, 16-bit samples and PackBits row lengths are big-endian. + header = struct.pack(">4sH6xHIIHH", b"8BPS", 1, channels, height, width, depth, 3) + return header + section(b"") + section(resources) + section(layers) + + +def packbits(row): + """Pack sequences of three or more repeated bytes and cap packets at 128.""" + output, literals = bytearray(), bytearray() + + def flush(): + if literals: + output.append(len(literals) - 1) + output.extend(literals) + literals.clear() + + pos = 0 + while pos < len(row): + end = pos + 1 + while end < min(len(row), pos + 128) and row[end] == row[pos]: + end += 1 + if end - pos >= 3: + flush() + output.extend((257 - (end - pos), row[pos])) + pos = end + else: + literals.append(row[pos]) + pos += 1 + if len(literals) == 128: + flush() + flush() + return bytes(output) + + +def predict(row, depth): + # The predictor resets at each row. At 16 bits the delta is a whole word. + mask = (1 << depth) - 1 + return samples([row[0]] + [(current - last) & mask for last, current in zip(row, row[1:])], depth) + + +def composite(planes, height, depth, compression): + rows = [row for plane in planes for row in plane] + assert len(rows) == len(planes) * height + if compression == RLE: + encoded = [packbits(samples(row, depth)) for row in rows] + payload = struct.pack(f">{len(encoded)}H", *map(len, encoded)) + b"".join(encoded) + else: + encode = predict if compression == PREDICTED_ZIP else samples + payload = b"".join(encode(row, depth) for row in rows) + if compression != RAW: + payload = zlib.compress(payload) + return struct.pack(">H", compression) + payload + + +def pixels(depth, alpha=False): + """Straight RGB(A) with repeated bytes, wrapped deltas and transparent edges.""" + maximum = (1 << depth) - 1 + scale = maximum // 255 + for y in range(HEIGHT): + for x in range(WIDTH): + if x < 128: + rgb = (0, maximum, 0) if y % 2 else (maximum, 0, maximum) + else: + # For 16-bit cases, low bytes deliberately differ from high bytes. + rgb = tuple(((x * dx + y * dy) * scale + y * 31 + c * 79) & maximum + for c, (dx, dy) in enumerate(((27, 3), (83, 41), (9, 13)))) + if alpha: + coverage = (0, 64, 128, 179, 255)[min(x, WIDTH - 1 - x, 4)] * scale + if 12 < x < WIDTH - 12: + coverage = (64, 255, 128, 179, 255)[(x + y) % 5] * scale if x >= 128 else maximum + yield (*rgb, coverage) + else: + yield rgb + + +def small_psd(depth=8, compression=RAW, channels="rgb", icc=None, layers=b"", resources=b""): + alpha = channels == "rgba" + maximum = (1 << depth) - 1 + pixels_on_disk = list(pixels(depth, alpha)) + if alpha: + # The saved merged RGB is white-matted. TIFF and the numeric oracle + # below use straight RGB and can catch failure to remove that matte. + pixels_on_disk = [tuple(maximum - a + (v * a + maximum // 2) // maximum for v in rgb) + (a,) + for *rgb, a in pixels_on_disk] + layers = layer_info(depth, -1, tagged=depth == 16) + elif channels in ("spot", "aux"): + pixels_on_disk = [(*rgb, (i * 59) & maximum) for i, rgb in enumerate(pixels_on_disk)] + resources += auxiliary_channel(channels == "spot") + layers = layer_info(depth, 1, tagged=depth == 16) + channels = len(pixels_on_disk[0]) + if icc is not None: + resources += resource(1039, icc, name=b"ICC name") + planes = [[plane[y:y + WIDTH] for y in range(0, len(plane), WIDTH)] for plane in zip(*pixels_on_disk)] + return prefix(WIDTH, HEIGHT, depth, channels, resources, layers) + composite(planes, HEIGHT, depth, compression) + + +def srgb_decode(value): + return value / 12.92 if value <= 0.04045 else ((value + 0.055) / 1.055) ** 2.4 + + +def srgb_encode(value): + return 12.92 * value if value <= 0.0031308 else 1.055 * value ** (1 / 2.4) - 0.055 + + +def rgb_profile(gamma=None): + """D50-adapted Rec.709 colorants with an sRGB TRC or a synthetic power TRC.""" + def xyz(values): + return b"XYZ " + bytes(4) + struct.pack(">3i", *(round(v * 65536) for v in values)) + + name = b"sRGB\0" if gamma is None else b"Synthetic RGB calibration\0" + white = xyz((0.9642, 1, 0.8249)) + curve = b"curv" + bytes(4) + if gamma is None: + curve += struct.pack(">I1024H", 1024, *(round(65535 * srgb_decode(i / 1023)) for i in range(1024))) + else: + curve += struct.pack(">IH", 1, round(gamma * 256)) + tags = [(b"desc", b"desc" + bytes(4) + section(name) + bytes(78)), + (b"cprt", b"text" + bytes(4) + b"Synthetic fixture\0"), + (b"wtpt", white), + (b"rXYZ", xyz((0.4360747, 0.2225045, 0.0139322))), + (b"gXYZ", xyz((0.3850649, 0.7168786, 0.0971045))), + (b"bXYZ", xyz((0.1430804, 0.0606169, 0.7141733)))] + body, table = bytearray(), bytearray(struct.pack(">I", len(tags) + 3)) + start = 132 + 12 * (len(tags) + 3) + for tag, data in tags: + table += struct.pack(">4sII", tag, start + len(body), len(data)) + body += padded(data, 4) + for tag in (b"rTRC", b"gTRC", b"bTRC"): + table += struct.pack(">4sII", tag, start + len(body), len(curve)) + body += padded(curve, 4) + header = bytearray(128) + struct.pack_into(">I", header, 0, 128 + len(table) + len(body)) + header[8:24] = b"\x02\x10\0\0mntrRGB XYZ " + struct.pack_into(">6H", header, 24, 2026, 1, 1, 0, 0, 0) + header[36:40] = b"acsp" + header[68:80] = white[8:] + return bytes(header + table + body) + + +def write_tiff(path, width, height, depth, values, endian, icc=None): + """Classic TIFF, one uncompressed strip of chunky, unassociated samples.""" + values = list(values) + channels = len(values[0]) + data = bytearray(b"II" if endian == "<" else b"MM") + data += struct.pack(endian + "HI", 42, 0) + payload = samples([sample for pixel in values for sample in pixel], depth, endian) + data += padded(payload, 2) + tags = [(256, 4, [width]), (257, 4, [height]), (258, 3, [depth] * channels), + (259, 3, [1]), (262, 3, [2]), (273, 4, [8]), (277, 3, [channels]), + (278, 4, [height]), (279, 4, [len(payload)]), (284, 3, [1])] + if channels == 4: + tags.append((338, 3, [2])) + if icc is not None: + tags.append((34675, 7, icc)) + entries = [] + for tag, kind, items in sorted(tags): + value = items if kind == 7 else struct.pack(endian + {3: "H", 4: "I"}[kind] * len(items), *items) + if len(value) > 4: + offset = len(data) + data += padded(value, 2) + value = struct.pack(endian + "I", offset) + entries.append(struct.pack(endian + "HHI", tag, kind, len(items)) + value.ljust(4, b"\0")) + struct.pack_into(endian + "I", data, 4, len(data)) + path.write_bytes(data + struct.pack(endian + "H", len(entries)) + b"".join(entries) + bytes(4)) + + +def read_png(path): + """Decode ThumbGen's 8-bit noninterlaced RGB(A) PNG and check chunk CRCs.""" + data = path.read_bytes() + assert data[:8] == b"\x89PNG\r\n\x1a\n", path + offset, compressed = 8, bytearray() + while offset < len(data): + length, kind = struct.unpack_from(">I4s", data, offset) + tag = data[offset + 4:offset + 8 + length] + assert zlib.crc32(tag) == struct.unpack_from(">I", data, offset + 8 + length)[0], path + offset += 12 + length + if kind == b"IHDR": + width, height, depth, colour, compression, filtering, interlace = struct.unpack(">IIBBBBB", tag[4:]) + elif kind == b"IDAT": + compressed += tag[4:] + elif kind == b"IEND": + assert offset == len(data) + break + assert kind == b"IEND" and depth == 8 and colour in (2, 6) and (compression, filtering, interlace) == (0, 0, 0) + bands = 3 if colour == 2 else 4 + raw = zlib.decompress(compressed) + stride = width * bands + assert len(raw) == height * (stride + 1) + previous, output = bytearray(stride), [] + for offset in range(0, len(raw), stride + 1): + mode, row = raw[offset], bytearray(raw[offset + 1:offset + stride + 1]) + assert mode in range(5) + for i in range(stride): + left = row[i - bands] if i >= bands else 0 + up = previous[i] + corner = previous[i - bands] if i >= bands else 0 + p = left + up - corner + paeth = min((left, up, corner), key=lambda sample: abs(p - sample)) + row[i] = (row[i] + (0, left, up, (left + up) // 2, paeth)[mode]) & 255 + output.extend(tuple(row[i:i + bands]) for i in range(0, stride, bands)) + previous = row + return width, height, output + + +def write_stress_psd(path, width, height, depth, compression, alpha): + """Write one bounded fixture at a time, caching a few fixed-seed row patterns.""" + rng = random.Random(42021) + maximum = (1 << depth) - 1 + channels = 4 if alpha else 3 + layers = layer_info(depth, -1, tagged=depth == 16) if alpha else b"" + # Long constant spans keep Raw/RLE and ZIP practical while still varying + # channels, rows and columns. RGBA rows have white-matted transparent edges. + rows = [] + encode = predict if compression == PREDICTED_ZIP else samples + for c in range(channels): + patterns = [] + for _ in range(4): + values = [] + for block in range(8): + a = (0, maximum // 2, maximum, maximum)[min(block, 7 - block, 3)] if alpha else maximum + colour = rng.randrange(maximum + 1) + value = a if c == 3 else maximum - a + colour * a // maximum + values.extend([value] * ((block + 1) * width // 8 - block * width // 8)) + packed = encode(values, depth) + patterns.append(packbits(packed) if compression == RLE else packed) + rows.append(patterns) + with path.open("wb") as stream: + stream.write(prefix(width, height, depth, channels, layers=layers)) + stream.write(struct.pack(">H", compression)) + if compression == RLE: + for plane in rows: + stream.write(b"".join(struct.pack(">H", len(plane[y % 4])) for y in range(height))) + compressor = zlib.compressobj(1) if compression in (ZIP, PREDICTED_ZIP) else None + for plane in rows: + for y in range(height): + row = plane[y % 4] + stream.write(compressor.compress(row) if compressor else row) + if compressor: + stream.write(compressor.flush()) diff --git a/tests/test_bounded_psd_cli.py b/tests/test_bounded_psd_cli.py new file mode 100644 index 0000000..1ced02d --- /dev/null +++ b/tests/test_bounded_psd_cli.py @@ -0,0 +1,474 @@ +"""Public PSD composite regressions. Python 3.9+, standard library only.""" +import argparse +import json +import os +from pathlib import Path +import struct +import subprocess +import sys +import tempfile +import threading +import unittest +import zlib + +from psd_fixtures import (HEIGHT, LAYER_RGB, PREDICTED_ZIP, RAW, RLE, WIDTH, ZIP, + layer_info, packbits, pixels, predict, prefix, read_png, + rgb_profile, small_psd, srgb_encode, version_info, + write_stress_psd, write_tiff) + + +PROJECT_CONFIG = """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 fitted(width, height, size): + scale = min(1, size[0] / width, size[1] / height) + return max(1, int(width * scale + .5)), max(1, int(height * scale + .5)) + + +def srgb_from_gamma(value, gamma): + return srgb_encode(value ** gamma) + + +def oracle(depth, alpha, transfer=lambda value: value): + maximum = (1 << depth) - 1 + for sample in pixels(depth, alpha): + rgb = tuple(round(255 * transfer(value / maximum)) for value in sample[:3]) + if alpha: + a = round(255 * sample[3] / maximum) + yield (*(rgb if a else (0, 0, 0)), a) + else: + yield rgb + + +def check_fixture_encoding(): + assert packbits(bytes(128) + b"\xde\xad") == b"\x81\0\x01\xde\xad" + increasing = bytes(range(129)) + assert packbits(increasing) == b"\x7f" + increasing[:128] + b"\0\x80" + assert predict([250, 3, 255, 0], 8) == bytes((250, 9, 252, 1)) + assert predict([0xfffd, 3, 0xab02, 0x00ff], 16).hex() == "fffd0006aaff55fd" + for depth in (8, 16): + for channels in ("rgb", "rgba", "spot", "aux"): + for codec in (RAW, RLE, ZIP, PREDICTED_ZIP): + data = small_psd(depth, codec, channels) + assert struct.unpack_from(">4sH6xHIIHH", data) == ( + b"8BPS", 1, 3 if channels == "rgb" else 4, HEIGHT, WIDTH, depth, 3) + offset = 26 + for _ in range(3): + offset += 4 + struct.unpack_from(">I", data, offset)[0] + assert struct.unpack_from(">H", data, offset)[0] == codec + payload = data[offset + 2:] + row_count = HEIGHT * (3 if channels == "rgb" else 4) + byte_count = WIDTH * row_count * (depth // 8) + if codec == RAW: + assert len(payload) == byte_count + elif codec == RLE: + sizes = struct.unpack_from(f">{row_count}H", payload) + assert all(sizes) and sum(sizes) + 2 * row_count == len(payload) + else: + assert len(zlib.decompress(payload)) == byte_count + assert list(oracle(8, True))[:3] == [(0, 0, 0, 0), (255, 0, 255, 64), (255, 0, 255, 128)] + print("PSD fixture encodings verified") + + +class CLI(unittest.TestCase): + def setUp(self): + tmp = tempfile.TemporaryDirectory(prefix="thumbgen-psd-") + self.addCleanup(tmp.cleanup) + self.root = Path(tmp.name) + + def fixture(self, name, data): + path = self.root / (name + ".psd") + path.write_bytes(data) + return path + + def command(self, *args, status=0, ocio=None): + command = [str(EXE), *map(str, args), "--json"] + env = ENV if ocio is None else dict(ENV, OCIO=str(ocio)) + run = subprocess.run(command, env=env, capture_output=True, text=True, encoding="utf-8", timeout=60) + try: + records = [json.loads(line) for line in run.stdout.splitlines()] + except json.JSONDecodeError as error: + self.fail(f"{command}: invalid JSON ({error})\n{run.stdout}\n{run.stderr}") + failures = [(record.get("id"), record["error"]) for record in records if "error" in record] + self.assertEqual(run.returncode, status, (command, failures, run.stderr)) + self.assertTrue(records and all(record["schema_version"] == 1 for record in records), records) + return records + + def convert(self, path, name, *args, size=(WIDTH, HEIGHT), status=0, ocio=None): + output = self.root / (name + ".png") + records = self.command("convert", path, "--output", output, "--size", f"{size[0]}x{size[1]}", + "--format", "png", "--background", "transparent", "--threads", 1, + "--thread-budget", 1, *args, status=status, ocio=ocio) + result = records[0] + self.assertEqual(result["type"], "result", records) + self.assertEqual(result["ok"], status == 0, result) + self.assertEqual(output.exists(), status == 0, result) + return result, output + + def job(self, name, path, sizes, **options): + return dict(id=name, input=str(path), options=options, outputs=[ + dict(path=str(self.root / f"{name}-{index}.png"), size=list(size), format="png") + for index, size in enumerate(sizes)]) + + def batch(self, jobs, status=0, budget=512): + manifest = self.root / "jobs.json" + manifest.write_text(json.dumps(dict(schema_version=1, + defaults=dict(threads=1, background="transparent"), + execution=dict(workers=1, thread_budget=1, memory_budget_mib=budget), + jobs=jobs)), encoding="utf-8") + records = self.command("batch", "--manifest", manifest, status=status) + results = [record for record in records if record["type"] == "result"] + self.assertEqual([result["id"] for result in results], [job["id"] for job in jobs], records) + self.assertEqual(records[-1]["type"], "summary", records) + return results + + def check_pixels(self, actual, expected, tolerance=0): + expected = list(expected) + self.assertEqual(len(actual), len(expected)) + for i, (a, b) in enumerate(zip(actual, expected)): + # PNG writers may omit a fully opaque alpha channel. + self.assertEqual(a[3] if len(a) == 4 else 255, b[3] if len(b) == 4 else 255, (i, a, b)) + if max(abs(x - y) for x, y in zip(a[:3], b[:3])) > tolerance: + self.fail(f"pixel {i}: got {a}, expected {b}, tolerance {tolerance}") + + def output_pixels(self, result, job, dimensions): + self.assertTrue(result["ok"], result) + self.assertEqual(len(result["outputs"]), len(job["outputs"]), result) + self.assertGreater(result["execution"]["admission_mib"], 0, result) + images = [] + for output, request in zip(result["outputs"], job["outputs"]): + size = fitted(*dimensions, request["size"]) + self.assertEqual(output["status"], "success", output) + self.assertEqual(Path(output["path"]), Path(request["path"]), output) + self.assertEqual((output["width"], output["height"]), size, output) + width, height, image = read_png(Path(output["path"])) + self.assertEqual((width, height), size, output) + images.append(image) + return images + + def test_legacy_inspect_and_part_selection(self): + source = self.fixture("legacy", small_psd(layers=layer_info(8, 1))) + inspection = self.command("inspect", source)[0] + self.assertEqual(inspection["type"], "inspection", inspection) + self.assertTrue(inspection["ok"], inspection) + self.assertEqual([(part["part"], part["name"], part["width"], part["height"], part["channels"]) + for part in inspection["parts"]], + [(0, "", WIDTH, HEIGHT, ["R", "G", "B"]), (1, "Layer", 2, 2, ["R", "G", "B"])]) + for name, opts in (("index", ("--part", 1)), ("name", ("--part-name", "Layer"))): + result, output = self.convert(source, name, *opts) + self.assertEqual(result["selection"]["chosen"]["part"], 1, result) + width, height, image = read_png(output) + self.assertEqual((width, height), (2, 2)) + self.check_pixels(image, [LAYER_RGB] * 4, 1) + result, _ = self.convert(source, "absent", "--part", 9, status=4) + self.assertEqual(result["error"]["code"], "part_not_found", result) + result, output = self.convert(source, "composite", "--part", 0) + self.assertEqual(result["selection"]["chosen"]["part"], 0, result) + self.check_pixels(read_png(output)[2], oracle(8, False), 1) + + def test_baseline_raw_and_rle_rgb(self): + jobs = [self.job(name, self.fixture(name, small_psd(depth, codec)), [(WIDTH, HEIGHT), (173, 9)]) + for depth in (8, 16) for codec in (RAW, RLE) for name in (f"rgb-{depth}-{codec}",)] + for result, job in zip(self.batch(jobs), jobs): + with self.subTest(id=job["id"]): + image = self.output_pixels(result, job, (WIDTH, HEIGHT))[0] + depth = int(job["id"].split("-")[1]) + self.check_pixels(image, oracle(depth, False), 1) + + def test_compression_and_transparency_matrix(self): + sizes = [(WIDTH, HEIGHT), (173, 7), (67, 6)] + jobs, cases = [], [] + for depth in (8, 16): + for channels in ("rgb", "rgba", "spot", "aux"): + for codec in (RAW, RLE, ZIP, PREDICTED_ZIP): + name = f"{channels}-{depth}-{codec}" + jobs.append(self.job(name, self.fixture(name, small_psd(depth, codec, channels)), sizes)) + cases.append((depth, channels == "rgba")) + results = self.batch(jobs) + for job, result, (depth, alpha) in zip(jobs, results, cases): + with self.subTest(id=job["id"]): + selection = result["selection"]["chosen"] + self.assertEqual(selection["part"], 0, result) + self.assertEqual(selection["channels"], ["R", "G", "B"] + (["A"] if alpha else []), result) + image = self.output_pixels(result, job, (WIDTH, HEIGHT))[0] + self.check_pixels(image, oracle(depth, alpha), 3 if depth == 8 and alpha else 1) + + def test_bounded_predicted_zip_admission(self): + # Cross the 8 MP bounded-path threshold without a large on-disk fixture. + width, height, depth = 4096, 2048, 16 + source = self.root / "bounded.psd" + write_stress_psd(source, width, height, depth, PREDICTED_ZIP, True) + # The two samplers and native/float blocks fit this limit while a + # full RGBA float raster and its packed copy need 256 MiB. + job = self.job("bounded", source, [(173, 131), (64, 64)], max_decode_mib=72) + result = self.batch([job], budget=336)[0] + images = self.output_pixels(result, job, (width, height)) + self.assertLessEqual(result["execution"]["admission_mib"], 72, result) + self.assertEqual(result["decoded_mib"], width * height * 8 / (1024 * 1024), result) + for image, request in zip(images, job["outputs"]): + ow, oh = fitted(width, height, request["size"]) + midline = image[(oh // 2) * ow:(oh // 2 + 1) * ow] + self.assertEqual(midline[0][3], 0) + self.assertEqual(midline[ow // 2][3], 255) + self.assertEqual(midline[-1][3], 0) + + def test_zip_inspect_composite(self): + source = self.fixture("inspect-zip", small_psd(16, PREDICTED_ZIP, "rgba")) + inspection = self.command("inspect", source)[0] + self.assertTrue(inspection["ok"], inspection) + self.assertEqual([(part["part"], part["width"], part["height"], part["channels"]) + for part in inspection["parts"]], [(0, WIDTH, HEIGHT, ["R", "G", "B", "A"])]) + result, output = self.convert(source, "zip-part-zero", "--part", 0) + self.assertEqual(result["selection"]["chosen"]["part"], 0, result) + self.check_pixels(read_png(output)[2], oracle(16, True), 1) + + def test_icc_with_lossless_reference_and_config_precedence(self): + gamma = 1.75 + icc = rgb_profile(gamma) + source = self.fixture("calibrated", small_psd(16, PREDICTED_ZIP, "rgba", icc=icc)) + srgb = self.fixture("srgb", small_psd(8, RAW, icc=rgb_profile())) + invalid = self.fixture("invalid-icc", small_psd(8, ZIP, icc=icc[:40])) + untagged = self.fixture("untagged", small_psd()) + config = self.root / "project.ocio" + config.write_text(PROJECT_CONFIG, encoding="utf-8") + for name, path, opts, inherited, expected, tolerance in ( + ("implicit", source, (), None, oracle(16, True, lambda v: srgb_from_gamma(v, gamma)), 2), + ("inherited", source, (), config, oracle(16, True, lambda v: srgb_from_gamma(v, gamma)), 2), + ("builtin", source, ("--ocio-config", "ocio://default"), config, + oracle(16, True, lambda v: srgb_from_gamma(v, gamma)), 2), + ("srgb", srgb, (), None, oracle(8, False), 1), + ): + with self.subTest(case=name): + result, output = self.convert(path, name, *opts, ocio=inherited) + colour = result["colour"] + self.assertEqual(colour["basis"], "embedded_icc", result) + self.assertEqual(colour["icc"]["model"], "RGB", result) + self.assertEqual(colour["config_basis"], "explicit" if opts else "builtin", result) + self.assertEqual(colour["ocio_config"], "ocio://default", result) + self.check_pixels(read_png(output)[2], expected, tolerance) + + sizes = [(WIDTH, HEIGHT), (173, 7), (67, 6)] + jobs = [self.job("psd", source, sizes)] + for endian, name in (("<", "little"), (">", "big")): + tiff = self.root / (name + ".tiff") + write_tiff(tiff, WIDTH, HEIGHT, 16, pixels(16, True), endian, icc) + jobs.append(self.job(name, tiff, sizes)) + psd, little, big = [self.output_pixels(result, job, (WIDTH, HEIGHT)) + for result, job in zip(self.batch(jobs), jobs)] + for a, b, c in zip(psd, little, big): + self.check_pixels(b, c) + self.check_pixels(a, b, 2) + + result, _ = self.convert(invalid, "rejected-icc", status=4) + self.assertEqual(result["error"]["code"], "colour_input_unsupported", result) + result, _ = self.convert(source, "rejected-bridge", "--ocio-config", config, status=4) + self.assertEqual(result["error"]["code"], "colour_input_unsupported", result) + self.assertIn("bridge", result["error"]["message"].lower()) + for name, path, opts, inherited, basis, transfer in ( + ("override-invalid", invalid, ("--input-space", "sRGB"), None, "builtin", lambda v: v), + ("explicit-config", invalid, ("--input-space", "linear", "--ocio-config", config), + None, "explicit", lambda v: v ** .5), + ("inherited-config", untagged, ("--input-space", "linear"), config, "environment", lambda v: v ** .5), + ): + with self.subTest(case=name): + result, output = self.convert(path, name, *opts, ocio=inherited) + self.assertEqual(result["colour"]["basis"], "explicit", result) + self.assertEqual(result["colour"]["config_basis"], basis, result) + self.assertNotIn("icc", result["colour"]) + self.check_pixels(read_png(output)[2], oracle(8, False, transfer), 2) + + def test_corrupt_composites_do_not_publish(self): + byte_count = WIDTH * HEIGHT * 3 + raw = small_psd() + rle = small_psd(compression=RLE) + zip_file = small_psd(compression=ZIP) + predicted = small_psd(compression=PREDICTED_ZIP) + header = prefix(WIDTH, HEIGHT, 8, 3) + rle_table = len(header) + 2 + rle_offset = rle_table + 2 * 3 * HEIGHT + first_row_length = struct.unpack_from(">H", rle, rle_table)[0] + overflow = b"\x81\xff" * 3 # Three repeats of 128 exceed the 259-byte scanline. + bad_run = (rle[:rle_table] + struct.pack(">H", len(overflow)) + rle[rle_table + 2:rle_offset] + + overflow + rle[rle_offset + first_row_length:]) + missing = prefix(WIDTH, HEIGHT, 8, 3, version_info(False)) + bad_resource_length = (prefix(WIDTH, HEIGHT, 8, 3, b"8BIM\x04\x0f\0\0\0\0\0\x20") + + raw[len(header):]) + cases = { + "section-offset": (raw[:30] + struct.pack(">I", len(raw)) + raw[34:], "open_failed"), + "resource-offset": (bad_resource_length, "open_failed"), + "layer-offset": (raw[:34] + struct.pack(">I", len(raw)) + raw[38:], "open_failed"), + "little-endian-header": (struct.pack("<4sH6xHIIHH", b"8BPS", 1, 3, HEIGHT, WIDTH, 8, 3) + + raw[26:], "open_failed"), + "no-composite": (header + b"\0\0", "decode_failed"), + "unmerged-placeholder": (missing + raw[len(header):], "decode_failed"), + "raw-short": (raw[:-1], "decode_failed"), + "rle-short-table": (rle[:rle_offset - 1], "decode_failed"), + "rle-short-file": (rle[:-1], "decode_failed"), + "rle-row-overflow": (bad_run, "decode_failed"), + "zip-bad-zlib": (zip_file[:-1] + bytes((zip_file[-1] ^ 1,)), "decode_failed"), + "zip-truncated": (zip_file[:-3], "decode_failed"), + "predicted-truncated": (predicted[:-3], "decode_failed"), + "zip-extra-sample": (header + b"\0\2" + zlib.compress(bytes(byte_count + 1)), "decode_failed"), + "zip-short-image": (header + b"\0\2" + zlib.compress(bytes(byte_count - 1)), "decode_failed"), + "zip-trailing-stream": (zip_file + zlib.compress(b""), "decode_failed"), + } + # Check a valid job after the errors, including after the inflater jobs, + # so a failed job cannot leave a reused worker or batch in a broken state. + jobs = [self.job(name, self.fixture(name, data), [(WIDTH, HEIGHT), (80, 9)]) + for name, (data, _) in cases.items()] + jobs.append(self.job("valid", self.fixture("valid", predicted), [(WIDTH, HEIGHT)])) + results = self.batch(jobs, status=3) + for job, result in zip(jobs[:-1], results[:-1]): + with self.subTest(id=job["id"]): + self.assertFalse(result["ok"], result) + self.assertEqual(result["error"]["code"], cases[job["id"]][1], result) + self.assertFalse(any(Path(output["path"]).exists() for output in job["outputs"]), result) + self.check_pixels(self.output_pixels(results[-1], jobs[-1], (WIDTH, HEIGHT))[0], oracle(8, False), 1) + + def test_budget_refusal_does_not_publish(self): + source = self.fixture("budget", small_psd(16, PREDICTED_ZIP, "rgba", icc=rgb_profile(1.75))) + result, _ = self.convert(source, "decode-refused", "--max-decode-mib", 1, status=4) + self.assertEqual(result["error"]["code"], "decode_limit_exceeded", result) + result, _ = self.convert(source, "admission-refused", "--memory-budget-mib", 265, status=4) + self.assertEqual(result["error"]["code"], "task_memory_exceeds_budget", result) + self.assertGreater(result["execution"]["admission_mib"], 1, result) + + +def stress_batch(command, timeout): + """Measure the Linux worker high-water RSS when procfs exposes children.""" + with subprocess.Popen(command, env=ENV, stdout=subprocess.PIPE, stderr=subprocess.PIPE, + text=True, encoding="utf-8") as process: + done, peak_kib = threading.Event(), 0 + + def sample(): + nonlocal peak_kib + tasks = Path(f"/proc/{process.pid}/task") + while not done.wait(.05): + pids = set() + for children in tasks.glob("*/children"): + try: + pids.update(children.read_text().split()) + except OSError: + continue + for pid in pids: + try: + status = Path(f"/proc/{pid}/status").read_text() + except OSError: + continue + for line in status.splitlines(): + if line.startswith("VmHWM:"): + peak_kib = max(peak_kib, int(line.split()[1])) + + monitor = threading.Thread(target=sample) + if sys.platform.startswith("linux"): + monitor.start() + try: + stdout, stderr = process.communicate(timeout=timeout) + except subprocess.TimeoutExpired: + process.kill() + process.communicate() + raise + finally: + done.set() + if monitor.ident is not None: + monitor.join() + assert process.returncode == 0, (command, stdout, stderr) + records = [json.loads(line) for line in stdout.splitlines()] + return records, peak_kib / 1024 if peak_kib else None + + +def run_stress(task_timeout): + sources = [(12000, 6000, 8, False), (16000, 8000, 16, True)] + sizes = [(960, 960), (425, 260)] + codecs = [(RAW, "raw"), (RLE, "packbits"), (ZIP, "zip"), (PREDICTED_ZIP, "predicted-zip")] + memory_budget = 2048 + decode_budget = 512 + with tempfile.TemporaryDirectory(prefix="thumbgen-psd-stress-") as tmp: + root = Path(tmp) + jobs, dimensions = [], {} + for width, height, depth, alpha in sources: + for codec, name in codecs: + job_id = f"{width}-{depth}-{name}" + source = root / f"{job_id}.psd" + write_stress_psd(source, width, height, depth, codec, alpha) + dimensions[job_id] = width, height + jobs.append(dict(id=job_id, input=str(source), outputs=[ + dict(path=str(root / f"{job_id}-{size[0]}.jpg"), size=list(size), format="jpeg") + for size in sizes])) + manifest = root / "jobs.json" + manifest.write_text(json.dumps(dict(schema_version=1, + defaults=dict(threads=1, max_decode_mib=decode_budget, background="black"), + execution=dict(workers=1, thread_budget=1, memory_budget_mib=memory_budget, + task_timeout_ms=task_timeout * 1000), + jobs=jobs)), encoding="utf-8") + command = [str(EXE), "batch", "--manifest", str(manifest), "--json"] + records, peak = stress_batch(command, len(jobs) * task_timeout + 20) + results = [record for record in records if record["type"] == "result"] + assert [result["id"] for result in results] == [job["id"] for job in jobs], records + assert records[-1]["type"] == "summary", records + + reference = {} + for job, result in zip(jobs, results): + execution = result["execution"] + assert result["ok"] and len(result["outputs"]) == len(sizes), result + assert execution["admission_mib"] + execution["fixed_reserve_mib"] <= memory_budget, result + width, height = dimensions[job["id"]] + previews = [] + for output, request in zip(result["outputs"], job["outputs"]): + assert output["status"] == "success" and Path(output["path"]) == Path(request["path"]), output + assert (output["width"], output["height"]) == fitted(width, height, request["size"]), output + jpeg = Path(output["path"]).read_bytes() + assert len(jpeg) > 4 and jpeg.startswith(b"\xff\xd8") and jpeg.endswith(b"\xff\xd9"), output + previews.append(jpeg) + for request, expected, actual in zip(job["outputs"], reference.setdefault(width, previews), previews): + assert actual == expected, (job["id"], request["size"]) + print(json.dumps(dict(id=job["id"], width=width, height=height, + max_decode_mib=decode_budget, memory_budget_mib=memory_budget, + admission_mib=execution["admission_mib"], + estimated_task_mib=execution["estimated_task_mib"], wall_ms=execution["wall_ms"], + output_bytes=list(map(len, previews)))), flush=True) + print(json.dumps(dict(jobs=len(results), sampled_worker_peak_mib=peak)), flush=True) + + +if __name__ == "__main__": + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("--exe", type=Path) + parser.add_argument("--runtime-dir", type=Path) + mode = parser.add_mutually_exclusive_group() + mode.add_argument("--fixtures-only", action="store_true") + mode.add_argument("--stress", action="store_true", help="run only the opt-in 12K/16K matrix") + parser.add_argument("--task-timeout-seconds", type=int, default=60, help="stress timeout per batch job") + args, remaining = parser.parse_known_args() + if args.fixtures_only: + check_fixture_encoding() + else: + if args.exe is None or not args.exe.is_file(): + parser.error("--exe must name a ThumbGen executable") + if args.task_timeout_seconds < 1: + parser.error("--task-timeout-seconds must be positive") + EXE = args.exe.resolve() + ENV = dict(os.environ) + ENV.pop("OCIO", None) + if args.runtime_dir: + key = "PATH" if os.name == "nt" else "LD_LIBRARY_PATH" + ENV[key] = str(args.runtime_dir.resolve()) + os.pathsep + ENV.get(key, "") + if args.stress: + run_stress(args.task_timeout_seconds) + else: + unittest.main(argv=[sys.argv[0], *remaining])