fix(libScePngEnc): honor zlib compression levels #18387

Merged
Ondra97 merged 1 commit from upstream-pr/18387 into main 2026-11-16 05:55:53 +00:00
Ondra97 commented 2026-11-11 13:13:11 +00:00 (Migrated from github.com)

Imported from boykopovar/AnyPS5. Originally posted by Ondra97 on 2026-11-11T13:13:11Z.


What

compression_level=0 still compresses PNG data because stb treats the value as a search-quality setting and raises values below 5 to 5. Use the existing bundled zlibstatic compressor for levels 0–9, so zero produces stored DEFLATE blocks and positive levels use the requested zlib level. Keep row filtering and PNG chunk emission unchanged, and remove the unused stb writer implementation.

This restores the compression-control behavior promised by #227 and follows the libpng compression-level contract and zlib API. The static zlib archive is hidden from PRX exports. The PNG targets reuse the existing zlib submodule at its current pinned revision. Compressed byte sequences change; exact native PS5 compressed bytes remain unmeasured as recorded in the existing debt entry.

Regressions check stored-block structure, LEN/NLEN, Adler32 and a multi-block stream above 65535 bytes; levels 0–9 also decode to the expected pixels with the selected filters. A separate regression calls the actual scePngEncEncode export.

Tested

Windows 11 Pro 10.0.26300; AMD Ryzen 9 7900X; 32 GB RAM; NVIDIA RTX 4070 Ti SUPER (unused by these codec tests). WinLibs MinGW-w64 GCC 15.2.0 r7, CMake 4.3.1, Ninja, Release.

Base reproduction: 2ecc68bda2642fbd5b4c9fb799bc1da4aa3df191. Final tested commit: 887c2c6e51e6b926a773abaa43e9f15b71af1efc, based on ed4b2e4cd8940464c89a40f89a092062c2203cdd.

Metric Before (base) After (fix)
Shared encoder level-0 stored-block regression Fails Passes
scePngEncEncode level-0 stored-block regression Fails Passes

A fresh full-project configuration used BUILD_TESTING=ON and ANYPS5_RELINKER_ONLY=OFF, with exact current submodules. The project's configure_seed.py reused compiler-probe answers from this session's identical toolchain, dependency revisions and configure-check inputs; all runtime targets were built in the new isolated build directory.

cmake -S . -B build -G Ninja -DCMAKE_BUILD_TYPE=Release -DBUILD_TESTING=ON -DANYPS5_RELINKER_ONLY=OFF -DCMAKE_C_COMPILER=gcc -DCMAKE_CXX_COMPILER=g++
cmake --build build --target decoder_png_tests guest_png_enc_tests guest_png_encoder_isolation_tests guest_png_input_extent_tests guest_png_dec_tests guest_png_dec_input_control_tests nid_patcher --parallel 8
ctest --test-dir build -R '^(public_headers|decoder_png|guest_png_enc|guest_png_encoder_isolation|guest_png_input_extent|guest_png_dec(_input_control)?)$' -V
python tools/check_conventions.py --base origin/main

All seven selected tests passed: six runtime tests and the public-header audit. Export/import-table audits of raw and NID-patched PngEnc/PngDec copies found no exported host zlib API or zlib DLL dependency. PngEnc's complete export and DLL sets equal the base; NID patching preserved export counts (15 for PngEnc, 26 for PngDec). Standalone runtime tests used the raw linked PRX; standalone NID copies were audited statically. The combined-stack probe below additionally executes NID-resolved exports.

Conventions and git diff --check passed. Independent review of the complete patch found no introduced defect. Linux, macOS, console, titles and the full CTest suite were not tested.

Hosted Windows job 130544673152 passed for head 887c2c6e51e6b926a773abaa43e9f15b71af1efc; its changed-test selection ran guest_png_enc successfully (1/1). Conventions, library portability, intake and eligibility also passed. Linux and unrelated jobs were skipped.

Pre-opening python tools/pr_overlap.py --repo boykopovar/AnyPS5 --branch codex/fix-png-compression-level --jobs 8 checked 1,987 open PR heads and reported no overlap. A separate merge-tree check with #18382 head 65fa4e73c96d26721170675076e73e07aa6fe1cf also merged cleanly: its sample-depth/background extension and this compression change are independent. Additional Cairo runtime compatibility is recorded below.

Additional integration validation: current main 0effa485f96a4fcf8fef433a09cdd862c65b7767 plus #18361 (2464b95fe12373ab2a4b46024b6b29390d615935), #18370 (c8388f97ab26a188bd07751a2f5ba2afce058bc6) and #18387 (887c2c6e51e6b926a773abaa43e9f15b71af1efc), composed locally as 7b8bc0d80db09dee5e39bcdf5159d8b8791d9db9. A fresh full-project build passed all 10 focused PNG/JPEG runtime CTests and public_headers (11/11). A separate temporary PNG probe passed in fresh processes through both raw and production-NID-resolved exports with an isolated patched libc/kernel/PNG closure. It checks level-0 stored RGB/RGBA streams, literal decoded pixels, 1/7/full-image callback chunks with an error only after IEND, repeated decode without another callback and row padding. This is synthetic Windows integration coverage; no title or console run is claimed. Probe source and reproduction commands are included in #18387.

Combined-stack PNG raw/NID probe

Start at the main revision above, compose the three commits, configure the full build as documented, and save this source as build/nid_probe.cpp. Use the supported WinLibs toolchain on PATH. Each invocation runs in a separate process; the complete runtime DLL closure is staged beside the probe.

#define WIN32_LEAN_AND_MEAN
#define NOMINMAX
#include <windows.h>
#include "prx/libScePngEnc/include/Api.hpp"
#include "prx/libScePngDec/include/Api.hpp"
#include <algorithm>
#include <cstddef>
#include <cstdint>
#include <cstdio>
#include <span>
#include <stdexcept>
#include <string>
#include <vector>

static void Require(bool value, const char* message) {
    if (!value) throw std::runtime_error(message);
}

template<typename TFunction>
static TFunction Resolve(HMODULE module, const char* name) {
    const auto address = GetProcAddress(module, name);
    if (!address) throw std::runtime_error(std::string("missing export ") + name);
    return reinterpret_cast<TFunction>(address);
}

static std::uint32_t BigEndian32(const std::uint8_t* bytes) {
    return static_cast<std::uint32_t>(bytes[0]) << 24 | static_cast<std::uint32_t>(bytes[1]) << 16
        | static_cast<std::uint32_t>(bytes[2]) << 8 | bytes[3];
}

static void RequireStored(std::span<const std::uint8_t> png) {
    std::vector<std::uint8_t> data;
    for (std::size_t offset = 8; offset + 12 <= png.size();) {
        const std::size_t length = BigEndian32(png.data() + offset);
        Require(length <= png.size() - offset - 12, "PNG chunk extent");
        if (std::equal(png.begin() + offset + 4, png.begin() + offset + 8, "IDAT")) {
            data.insert(data.end(), png.begin() + offset + 8, png.begin() + offset + 8 + length);
        }
        offset += length + 12;
    }
    Require(data.size() >= 11 && (data[0] & 15) == 8, "zlib image stream");
    std::size_t offset = 2;
    bool final = false;
    while (!final) {
        Require(offset + 5 <= data.size() - 4, "stored block header");
        const auto header = data[offset++];
        Require((header & 6) == 0, "compression level 0 must use stored blocks");
        final = (header & 1) != 0;
        const unsigned length = data[offset] | static_cast<unsigned>(data[offset + 1]) << 8;
        const unsigned inverse = data[offset + 2] | static_cast<unsigned>(data[offset + 3]) << 8;
        Require((length ^ inverse) == 0xFFFF, "stored block LEN/NLEN");
        offset += 4;
        Require(length <= data.size() - offset - 4, "stored block extent");
        offset += length;
    }
    Require(offset + 4 == data.size(), "complete stored zlib stream");
}

struct Source {
    std::span<const std::uint8_t> png;
    std::size_t chunkSize;
    std::size_t offset = 0;
    std::size_t calls = 0;
};

static std::int32_t APS5_VABI ReadChunk(PngDecInputChunk* chunk, void* argument) {
    auto& source = *static_cast<Source*>(argument);
    ++source.calls;
    if (source.offset == source.png.size()) return -123;
    const auto count = std::min(source.chunkSize, source.png.size() - source.offset);
    chunk->data = source.png.data() + source.offset;
    chunk->size = static_cast<std::uint32_t>(count);
    chunk->reserved = 0;
    source.offset += count;
    return 0;
}

int main(int argc, char** argv) {
    if (argc != 3 && argc != 11) {
        std::fprintf(stderr, "usage: nid_probe <absolute encoder.prx> <absolute decoder.prx> [encQuery encCreate encEncode encDelete decQuery decCreate decControl decDelete]\n");
        return 2;
    }
    try {
        const char* names[] = {"scePngEncQueryMemorySize", "scePngEncCreate", "scePngEncEncode", "scePngEncDelete",
            "scePngDecQueryMemorySize", "scePngDecCreate", "scePngDecDecodeWithInputControl", "scePngDecDelete"};
        if (argc == 11) std::copy(argv + 3, argv + 11, names);
        const HMODULE encoder = LoadLibraryExA(argv[1], nullptr, LOAD_WITH_ALTERED_SEARCH_PATH);
        if (!encoder) throw std::runtime_error("encoder LoadLibrary failed: " + std::to_string(GetLastError()));
        const HMODULE decoder = LoadLibraryExA(argv[2], nullptr, LOAD_WITH_ALTERED_SEARCH_PATH);
        if (!decoder) throw std::runtime_error("decoder LoadLibrary failed: " + std::to_string(GetLastError()));
        const auto encQuery = Resolve<decltype(&scePngEncQueryMemorySize)>(encoder, names[0]);
        const auto encCreate = Resolve<decltype(&scePngEncCreate)>(encoder, names[1]);
        const auto encEncode = Resolve<decltype(&scePngEncEncode)>(encoder, names[2]);
        const auto encDelete = Resolve<decltype(&scePngEncDelete)>(encoder, names[3]);
        const auto decQuery = Resolve<decltype(&scePngDecQueryMemorySize)>(decoder, names[4]);
        const auto decCreate = Resolve<decltype(&scePngDecCreate)>(decoder, names[5]);
        const auto decControl = Resolve<decltype(&scePngDecDecodeWithInputControl)>(decoder, names[6]);
        const auto decDelete = Resolve<decltype(&scePngDecDelete)>(decoder, names[7]);
        const PngEncCreateParam encParam{sizeof(PngEncCreateParam), 0, 16, 4};
        const int encSize = encQuery(&encParam);
        Require(encSize > 0, "encoder memory query");
        std::vector<std::uint64_t> encWork((encSize + 7) / 8);
        void* encHandle = nullptr;
        Require(encCreate(&encParam, encWork.data(), encSize, &encHandle) == 0, "encoder create");
        constexpr std::uint32_t width = 16, height = 16, pitch = 68;
        std::vector<std::uint32_t> input(pitch * height / 4, 0xEEEEEEEE);
        auto* inputBytes = reinterpret_cast<std::uint8_t*>(input.data());
        for (std::uint32_t y = 0; y < height; ++y) {
            for (std::uint32_t x = 0; x < width; ++x) {
                const std::uint8_t pixel[] = {17, 34, 51, 68};
                std::copy(std::begin(pixel), std::end(pixel), inputBytes + y * pitch + x * 4);
            }
        }
        std::vector<std::uint8_t> output(8192);
        for (const std::uint16_t colorSpace : {3, 19}) {
            PngEncEncodeParam encode{inputBytes, output.data(), pitch * height, static_cast<std::uint32_t>(output.size()),
                width, height, pitch, 0, colorSpace, 8, 0, 0, 0};
            PngEncOutputInfo encodedInfo{};
            const int size = encEncode(encHandle, &encode, &encodedInfo);
            Require(size > 0 && static_cast<std::size_t>(size) <= output.size(), "encode result");
            Require(encodedInfo.data_size == static_cast<std::uint32_t>(size) && encodedInfo.processed_height == height, "encode metadata");
            const std::span<const std::uint8_t> png(output.data(), size);
            RequireStored(png);
            for (const std::size_t chunkSize : {std::size_t{1}, std::size_t{7}, png.size()}) {
                const PngDecCreateParam decParam{sizeof(PngDecCreateParam), 0, width};
                const int decSize = decQuery(&decParam);
                Require(decSize > 0, "decoder memory query");
                std::vector<std::uint64_t> decWork((decSize + 7) / 8);
                void* decHandle = nullptr;
                Require(decCreate(&decParam, decWork.data(), decSize, &decHandle) == 0, "decoder create");
                Source source{png, chunkSize};
                PngDecInputControlParam control{};
                control.input = ReadChunk;
                control.input_argument = &source;
                control.operation = 0x10;
                PngDecImageInfo info{};
                Require(decControl(decHandle, &control, &info) == 0, "stream parse");
                Require(info.image_width == width && info.image_height == height && info.color_space == colorSpace, "parsed metadata");
                std::vector<std::uint32_t> image(pitch * height / 4, 0xCCCCCCCC);
                control.operation = 0x20;
                control.image_mem_addr = image.data();
                control.image_mem_size = pitch * height;
                control.image_pitch = pitch;
                control.alpha_value = 0x77;
                Require(decControl(decHandle, &control, &info) == static_cast<std::int32_t>(width << 16 | height), "stream decode must stop at IEND");
                Require(source.calls == (png.size() + chunkSize - 1) / chunkSize, "no callback after IEND");
                const auto* bytes = reinterpret_cast<const std::uint8_t*>(image.data());
                for (std::uint32_t y = 0; y < height; ++y) {
                    for (std::uint32_t x = 0; x < width; ++x) {
                        const auto* pixel = bytes + y * pitch + x * 4;
                        Require(pixel[0] == 17 && pixel[1] == 34 && pixel[2] == 51 && pixel[3] == (colorSpace == 19 ? 68 : 0x77), "decoded literal RGBA pixels");
                    }
                    Require(image[y * pitch / 4 + width] == 0xCCCCCCCC, "output row padding preserved");
                }
                const auto calls = source.calls;
                Require(decControl(decHandle, &control, nullptr) == static_cast<std::int32_t>(width << 16 | height), "repeated decode");
                Require(source.calls == calls, "repeated decode makes no callback");
                Require(decDelete(decHandle) == 0, "decoder delete");
            }
        }
        Require(encDelete(encHandle) == 0, "encoder delete");
        FreeLibrary(decoder);
        FreeLibrary(encoder);
        std::puts("PASS: runtime exports, level-0 stored RGB/RGBA PNGs, literal pixels, IEND callback boundary, repeated decode, padding");
        return 0;
    } catch (const std::exception& error) {
        std::fprintf(stderr, "FAIL: %s\n", error.what());
        return 1;
    }
}

git cherry-pick 2464b95fe12373ab2a4b46024b6b29390d615935 c8388f97ab26a188bd07751a2f5ba2afce058bc6 887c2c6e51e6b926a773abaa43e9f15b71af1efc
cmake --build build --target decoder_png_tests guest_png_enc_tests guest_png_encoder_isolation_tests guest_png_input_extent_tests guest_png_dec_tests guest_png_dec_input_control_tests decoder_jpeg_tests guest_jpeg_dec_tests guest_jpeg_dec_input_control_tests guest_jpeg_input_extent_tests nid_patcher --parallel 8
ctest --test-dir build -R '^(public_headers|decoder_(png|jpeg)|guest_png_(enc|encoder_isolation|input_extent|dec(_input_control)?)|guest_jpeg_(dec(_input_control)?|input_extent))$' -V
g++ -std=c++20 -O2 -fasynchronous-unwind-tables -static -static-libgcc -static-libstdc++ -Icore/libs build/nid_probe.cpp -o build/nid_probe.exe
$build = (Resolve-Path build).Path
$raw = "$build/runtime-raw"
$nid = "$build/runtime-nid"
foreach ($dir in @($raw,$nid)) {
    New-Item -ItemType Directory -Path $dir -Force | Out-Null
    Copy-Item "$build/nid_probe.exe" "$dir/nid_probe.exe"
    foreach ($dll in @('libstdc++-6.dll','libgcc_s_seh-1.dll','libwinpthread-1.dll')) { Copy-Item "$build/tests/$dll" "$dir/$dll" }
    foreach ($module in @('libc','libkernel','libScePngEnc','libScePngDec')) { Copy-Item "$build/core/libs/libs/unpatched/$module.prx" "$dir/$module.prx" }
}
& "$raw/nid_probe.exe" "$raw/libScePngEnc.prx" "$raw/libScePngDec.prx"
& "$build/core/libs/nid_patcher.exe" --write-export-list "$build/core/libs/libs/unpatched/libc.prx" "$nid/libc.exports"
& "$build/core/libs/nid_patcher.exe" libc "$nid/libc.prx"
foreach ($module in @('libkernel','libScePngEnc','libScePngDec')) { & "$build/core/libs/nid_patcher.exe" $module --preserve-export-list "$nid/libc.exports" "$nid/$module.prx" }
$ids = (python -c 'import json,sys; sys.path.insert(0,"tools"); from nid_names import compute_nid; print(json.dumps([compute_nid(n) for n in ["scePngEncQueryMemorySize","scePngEncCreate","scePngEncEncode","scePngEncDelete","scePngDecQueryMemorySize","scePngDecCreate","scePngDecDecodeWithInputControl","scePngDecDelete"]]))') | ConvertFrom-Json
& "$nid/nid_probe.exe" "$nid/libScePngEnc.prx" "$nid/libScePngDec.prx" @ids

Observed result in both raw and NID modes: PASS: runtime exports, level-0 stored RGB/RGBA PNGs, literal pixels, IEND callback boundary, repeated decode, padding.

Cairo compatibility validation: after reviewing the complete introduced diff 2ecc68bda2642fbd5b4c9fb799bc1da4aa3df191..65fa4e73c96d26721170675076e73e07aa6fe1cf, I three-way merged that exact #18382 head into the local three-PR validation stack. The resulting local commit is 72659301b8c884f06ff5358831bf59d92e2da9c0 (tree a9c723b70b0efdcd79db6988a93246b41cdae132). Rebuilding guest_cairo_png_tests and the ten codec runtime targets, then adding guest_cairo_png to the focused CTest selection above, passed all 12 checks including public_headers. This exercises Cairo's 16-bit floating-point PNG outputs, white bKGD, eight image formats, subsurfaces and callback failures with the zlib compressor. The raw and NID PNG probes also passed again against freshly copied, hash-verified rebuilt modules. Cairo changes are confined to the local validation tree; the published PNG compression patch is unchanged.

Checklist

  • Based on current main; no other open PR implements the same functions
  • One topic per PR; follow-ups go in a new PR
  • No comments in code except technical debt
  • Unimplemented paths throw (NotImplemented_nid_no_patch); silent stubs are listed under Silent stubs in their library's technical debt file
  • No notes, investigation .md files or images added to the repository (attach them to this PR)
  • New third-party code is a submodule built from source
  • Generic behaviour, not specific to one title
  • Depends on: none
  • Fixes: none
  • Unblocks: none
  • GPUs tested: n/a
  • AI-assisted: yes
<!-- greyfinch-sync:boykopovar/AnyPS5:issue:5260110622 --> Imported from [boykopovar/AnyPS5](https://github.com/boykopovar/AnyPS5/pull/18387). Originally posted by [Ondra97](https://github.com/Ondra97) on 2026-11-11T13:13:11Z. --- ### What `compression_level=0` still compresses PNG data because stb treats the value as a search-quality setting and raises values below 5 to 5. Use the existing bundled `zlibstatic` compressor for levels 0–9, so zero produces stored DEFLATE blocks and positive levels use the requested zlib level. Keep row filtering and PNG chunk emission unchanged, and remove the unused stb writer implementation. This restores the compression-control behavior promised by #227 and follows the [libpng compression-level contract](https://www.libpng.org/pub/png/libpng-1.2.5-manual.html#section-V) and [zlib API](https://zlib.net/manual.html). The static zlib archive is hidden from PRX exports. The PNG targets reuse the existing zlib submodule at its current pinned revision. Compressed byte sequences change; exact native PS5 compressed bytes remain unmeasured as recorded in the existing debt entry. Regressions check stored-block structure, LEN/NLEN, Adler32 and a multi-block stream above 65535 bytes; levels 0–9 also decode to the expected pixels with the selected filters. A separate regression calls the actual `scePngEncEncode` export. ### Tested <!-- OS, title or homebrew, what was checked. "Not tested" is a valid answer. A performance change: the summary lines of main and of this PR from the same machine and scene, with the traces attached, captured as the Performance report issue form describes. --> Windows 11 Pro 10.0.26300; AMD Ryzen 9 7900X; 32 GB RAM; NVIDIA RTX 4070 Ti SUPER (unused by these codec tests). WinLibs MinGW-w64 GCC 15.2.0 r7, CMake 4.3.1, Ninja, Release. Base reproduction: `2ecc68bda2642fbd5b4c9fb799bc1da4aa3df191`. Final tested commit: `887c2c6e51e6b926a773abaa43e9f15b71af1efc`, based on `ed4b2e4cd8940464c89a40f89a092062c2203cdd`. | Metric | Before (base) | After (fix) | | --- | --- | --- | | Shared encoder level-0 stored-block regression | Fails | Passes | | `scePngEncEncode` level-0 stored-block regression | Fails | Passes | A fresh full-project configuration used `BUILD_TESTING=ON` and `ANYPS5_RELINKER_ONLY=OFF`, with exact current submodules. The project's `configure_seed.py` reused compiler-probe answers from this session's identical toolchain, dependency revisions and configure-check inputs; all runtime targets were built in the new isolated build directory. ```sh cmake -S . -B build -G Ninja -DCMAKE_BUILD_TYPE=Release -DBUILD_TESTING=ON -DANYPS5_RELINKER_ONLY=OFF -DCMAKE_C_COMPILER=gcc -DCMAKE_CXX_COMPILER=g++ cmake --build build --target decoder_png_tests guest_png_enc_tests guest_png_encoder_isolation_tests guest_png_input_extent_tests guest_png_dec_tests guest_png_dec_input_control_tests nid_patcher --parallel 8 ctest --test-dir build -R '^(public_headers|decoder_png|guest_png_enc|guest_png_encoder_isolation|guest_png_input_extent|guest_png_dec(_input_control)?)$' -V python tools/check_conventions.py --base origin/main ``` All seven selected tests passed: six runtime tests and the public-header audit. Export/import-table audits of raw and NID-patched PngEnc/PngDec copies found no exported host zlib API or zlib DLL dependency. PngEnc's complete export and DLL sets equal the base; NID patching preserved export counts (15 for PngEnc, 26 for PngDec). Standalone runtime tests used the raw linked PRX; standalone NID copies were audited statically. The combined-stack probe below additionally executes NID-resolved exports. Conventions and `git diff --check` passed. Independent review of the complete patch found no introduced defect. Linux, macOS, console, titles and the full CTest suite were not tested. Hosted [Windows job 130544673152](https://github.com/boykopovar/AnyPS5/actions/runs/43027145061/job/130544673152) passed for head `887c2c6e51e6b926a773abaa43e9f15b71af1efc`; its changed-test selection ran `guest_png_enc` successfully (1/1). Conventions, library portability, intake and eligibility also passed. Linux and unrelated jobs were skipped. Pre-opening `python tools/pr_overlap.py --repo boykopovar/AnyPS5 --branch codex/fix-png-compression-level --jobs 8` checked 1,987 open PR heads and reported no overlap. A separate merge-tree check with #18382 head `65fa4e73c96d26721170675076e73e07aa6fe1cf` also merged cleanly: its sample-depth/background extension and this compression change are independent. Additional Cairo runtime compatibility is recorded below. Additional integration validation: current main `0effa485f96a4fcf8fef433a09cdd862c65b7767` plus #18361 (`2464b95fe12373ab2a4b46024b6b29390d615935`), #18370 (`c8388f97ab26a188bd07751a2f5ba2afce058bc6`) and #18387 (`887c2c6e51e6b926a773abaa43e9f15b71af1efc`), composed locally as `7b8bc0d80db09dee5e39bcdf5159d8b8791d9db9`. A fresh full-project build passed all 10 focused PNG/JPEG runtime CTests and `public_headers` (11/11). A separate temporary PNG probe passed in fresh processes through both raw and production-NID-resolved exports with an isolated patched libc/kernel/PNG closure. It checks level-0 stored RGB/RGBA streams, literal decoded pixels, 1/7/full-image callback chunks with an error only after IEND, repeated decode without another callback and row padding. This is synthetic Windows integration coverage; no title or console run is claimed. Probe source and reproduction commands are included in #18387. <details><summary>Combined-stack PNG raw/NID probe</summary> Start at the main revision above, compose the three commits, configure the full build as documented, and save this source as `build/nid_probe.cpp`. Use the supported WinLibs toolchain on PATH. Each invocation runs in a separate process; the complete runtime DLL closure is staged beside the probe. ```cpp #define WIN32_LEAN_AND_MEAN #define NOMINMAX #include <windows.h> #include "prx/libScePngEnc/include/Api.hpp" #include "prx/libScePngDec/include/Api.hpp" #include <algorithm> #include <cstddef> #include <cstdint> #include <cstdio> #include <span> #include <stdexcept> #include <string> #include <vector> static void Require(bool value, const char* message) { if (!value) throw std::runtime_error(message); } template<typename TFunction> static TFunction Resolve(HMODULE module, const char* name) { const auto address = GetProcAddress(module, name); if (!address) throw std::runtime_error(std::string("missing export ") + name); return reinterpret_cast<TFunction>(address); } static std::uint32_t BigEndian32(const std::uint8_t* bytes) { return static_cast<std::uint32_t>(bytes[0]) << 24 | static_cast<std::uint32_t>(bytes[1]) << 16 | static_cast<std::uint32_t>(bytes[2]) << 8 | bytes[3]; } static void RequireStored(std::span<const std::uint8_t> png) { std::vector<std::uint8_t> data; for (std::size_t offset = 8; offset + 12 <= png.size();) { const std::size_t length = BigEndian32(png.data() + offset); Require(length <= png.size() - offset - 12, "PNG chunk extent"); if (std::equal(png.begin() + offset + 4, png.begin() + offset + 8, "IDAT")) { data.insert(data.end(), png.begin() + offset + 8, png.begin() + offset + 8 + length); } offset += length + 12; } Require(data.size() >= 11 && (data[0] & 15) == 8, "zlib image stream"); std::size_t offset = 2; bool final = false; while (!final) { Require(offset + 5 <= data.size() - 4, "stored block header"); const auto header = data[offset++]; Require((header & 6) == 0, "compression level 0 must use stored blocks"); final = (header & 1) != 0; const unsigned length = data[offset] | static_cast<unsigned>(data[offset + 1]) << 8; const unsigned inverse = data[offset + 2] | static_cast<unsigned>(data[offset + 3]) << 8; Require((length ^ inverse) == 0xFFFF, "stored block LEN/NLEN"); offset += 4; Require(length <= data.size() - offset - 4, "stored block extent"); offset += length; } Require(offset + 4 == data.size(), "complete stored zlib stream"); } struct Source { std::span<const std::uint8_t> png; std::size_t chunkSize; std::size_t offset = 0; std::size_t calls = 0; }; static std::int32_t APS5_VABI ReadChunk(PngDecInputChunk* chunk, void* argument) { auto& source = *static_cast<Source*>(argument); ++source.calls; if (source.offset == source.png.size()) return -123; const auto count = std::min(source.chunkSize, source.png.size() - source.offset); chunk->data = source.png.data() + source.offset; chunk->size = static_cast<std::uint32_t>(count); chunk->reserved = 0; source.offset += count; return 0; } int main(int argc, char** argv) { if (argc != 3 && argc != 11) { std::fprintf(stderr, "usage: nid_probe <absolute encoder.prx> <absolute decoder.prx> [encQuery encCreate encEncode encDelete decQuery decCreate decControl decDelete]\n"); return 2; } try { const char* names[] = {"scePngEncQueryMemorySize", "scePngEncCreate", "scePngEncEncode", "scePngEncDelete", "scePngDecQueryMemorySize", "scePngDecCreate", "scePngDecDecodeWithInputControl", "scePngDecDelete"}; if (argc == 11) std::copy(argv + 3, argv + 11, names); const HMODULE encoder = LoadLibraryExA(argv[1], nullptr, LOAD_WITH_ALTERED_SEARCH_PATH); if (!encoder) throw std::runtime_error("encoder LoadLibrary failed: " + std::to_string(GetLastError())); const HMODULE decoder = LoadLibraryExA(argv[2], nullptr, LOAD_WITH_ALTERED_SEARCH_PATH); if (!decoder) throw std::runtime_error("decoder LoadLibrary failed: " + std::to_string(GetLastError())); const auto encQuery = Resolve<decltype(&scePngEncQueryMemorySize)>(encoder, names[0]); const auto encCreate = Resolve<decltype(&scePngEncCreate)>(encoder, names[1]); const auto encEncode = Resolve<decltype(&scePngEncEncode)>(encoder, names[2]); const auto encDelete = Resolve<decltype(&scePngEncDelete)>(encoder, names[3]); const auto decQuery = Resolve<decltype(&scePngDecQueryMemorySize)>(decoder, names[4]); const auto decCreate = Resolve<decltype(&scePngDecCreate)>(decoder, names[5]); const auto decControl = Resolve<decltype(&scePngDecDecodeWithInputControl)>(decoder, names[6]); const auto decDelete = Resolve<decltype(&scePngDecDelete)>(decoder, names[7]); const PngEncCreateParam encParam{sizeof(PngEncCreateParam), 0, 16, 4}; const int encSize = encQuery(&encParam); Require(encSize > 0, "encoder memory query"); std::vector<std::uint64_t> encWork((encSize + 7) / 8); void* encHandle = nullptr; Require(encCreate(&encParam, encWork.data(), encSize, &encHandle) == 0, "encoder create"); constexpr std::uint32_t width = 16, height = 16, pitch = 68; std::vector<std::uint32_t> input(pitch * height / 4, 0xEEEEEEEE); auto* inputBytes = reinterpret_cast<std::uint8_t*>(input.data()); for (std::uint32_t y = 0; y < height; ++y) { for (std::uint32_t x = 0; x < width; ++x) { const std::uint8_t pixel[] = {17, 34, 51, 68}; std::copy(std::begin(pixel), std::end(pixel), inputBytes + y * pitch + x * 4); } } std::vector<std::uint8_t> output(8192); for (const std::uint16_t colorSpace : {3, 19}) { PngEncEncodeParam encode{inputBytes, output.data(), pitch * height, static_cast<std::uint32_t>(output.size()), width, height, pitch, 0, colorSpace, 8, 0, 0, 0}; PngEncOutputInfo encodedInfo{}; const int size = encEncode(encHandle, &encode, &encodedInfo); Require(size > 0 && static_cast<std::size_t>(size) <= output.size(), "encode result"); Require(encodedInfo.data_size == static_cast<std::uint32_t>(size) && encodedInfo.processed_height == height, "encode metadata"); const std::span<const std::uint8_t> png(output.data(), size); RequireStored(png); for (const std::size_t chunkSize : {std::size_t{1}, std::size_t{7}, png.size()}) { const PngDecCreateParam decParam{sizeof(PngDecCreateParam), 0, width}; const int decSize = decQuery(&decParam); Require(decSize > 0, "decoder memory query"); std::vector<std::uint64_t> decWork((decSize + 7) / 8); void* decHandle = nullptr; Require(decCreate(&decParam, decWork.data(), decSize, &decHandle) == 0, "decoder create"); Source source{png, chunkSize}; PngDecInputControlParam control{}; control.input = ReadChunk; control.input_argument = &source; control.operation = 0x10; PngDecImageInfo info{}; Require(decControl(decHandle, &control, &info) == 0, "stream parse"); Require(info.image_width == width && info.image_height == height && info.color_space == colorSpace, "parsed metadata"); std::vector<std::uint32_t> image(pitch * height / 4, 0xCCCCCCCC); control.operation = 0x20; control.image_mem_addr = image.data(); control.image_mem_size = pitch * height; control.image_pitch = pitch; control.alpha_value = 0x77; Require(decControl(decHandle, &control, &info) == static_cast<std::int32_t>(width << 16 | height), "stream decode must stop at IEND"); Require(source.calls == (png.size() + chunkSize - 1) / chunkSize, "no callback after IEND"); const auto* bytes = reinterpret_cast<const std::uint8_t*>(image.data()); for (std::uint32_t y = 0; y < height; ++y) { for (std::uint32_t x = 0; x < width; ++x) { const auto* pixel = bytes + y * pitch + x * 4; Require(pixel[0] == 17 && pixel[1] == 34 && pixel[2] == 51 && pixel[3] == (colorSpace == 19 ? 68 : 0x77), "decoded literal RGBA pixels"); } Require(image[y * pitch / 4 + width] == 0xCCCCCCCC, "output row padding preserved"); } const auto calls = source.calls; Require(decControl(decHandle, &control, nullptr) == static_cast<std::int32_t>(width << 16 | height), "repeated decode"); Require(source.calls == calls, "repeated decode makes no callback"); Require(decDelete(decHandle) == 0, "decoder delete"); } } Require(encDelete(encHandle) == 0, "encoder delete"); FreeLibrary(decoder); FreeLibrary(encoder); std::puts("PASS: runtime exports, level-0 stored RGB/RGBA PNGs, literal pixels, IEND callback boundary, repeated decode, padding"); return 0; } catch (const std::exception& error) { std::fprintf(stderr, "FAIL: %s\n", error.what()); return 1; } } ``` ```powershell git cherry-pick 2464b95fe12373ab2a4b46024b6b29390d615935 c8388f97ab26a188bd07751a2f5ba2afce058bc6 887c2c6e51e6b926a773abaa43e9f15b71af1efc cmake --build build --target decoder_png_tests guest_png_enc_tests guest_png_encoder_isolation_tests guest_png_input_extent_tests guest_png_dec_tests guest_png_dec_input_control_tests decoder_jpeg_tests guest_jpeg_dec_tests guest_jpeg_dec_input_control_tests guest_jpeg_input_extent_tests nid_patcher --parallel 8 ctest --test-dir build -R '^(public_headers|decoder_(png|jpeg)|guest_png_(enc|encoder_isolation|input_extent|dec(_input_control)?)|guest_jpeg_(dec(_input_control)?|input_extent))$' -V g++ -std=c++20 -O2 -fasynchronous-unwind-tables -static -static-libgcc -static-libstdc++ -Icore/libs build/nid_probe.cpp -o build/nid_probe.exe $build = (Resolve-Path build).Path $raw = "$build/runtime-raw" $nid = "$build/runtime-nid" foreach ($dir in @($raw,$nid)) { New-Item -ItemType Directory -Path $dir -Force | Out-Null Copy-Item "$build/nid_probe.exe" "$dir/nid_probe.exe" foreach ($dll in @('libstdc++-6.dll','libgcc_s_seh-1.dll','libwinpthread-1.dll')) { Copy-Item "$build/tests/$dll" "$dir/$dll" } foreach ($module in @('libc','libkernel','libScePngEnc','libScePngDec')) { Copy-Item "$build/core/libs/libs/unpatched/$module.prx" "$dir/$module.prx" } } & "$raw/nid_probe.exe" "$raw/libScePngEnc.prx" "$raw/libScePngDec.prx" & "$build/core/libs/nid_patcher.exe" --write-export-list "$build/core/libs/libs/unpatched/libc.prx" "$nid/libc.exports" & "$build/core/libs/nid_patcher.exe" libc "$nid/libc.prx" foreach ($module in @('libkernel','libScePngEnc','libScePngDec')) { & "$build/core/libs/nid_patcher.exe" $module --preserve-export-list "$nid/libc.exports" "$nid/$module.prx" } $ids = (python -c 'import json,sys; sys.path.insert(0,"tools"); from nid_names import compute_nid; print(json.dumps([compute_nid(n) for n in ["scePngEncQueryMemorySize","scePngEncCreate","scePngEncEncode","scePngEncDelete","scePngDecQueryMemorySize","scePngDecCreate","scePngDecDecodeWithInputControl","scePngDecDelete"]]))') | ConvertFrom-Json & "$nid/nid_probe.exe" "$nid/libScePngEnc.prx" "$nid/libScePngDec.prx" @ids ``` Observed result in both raw and NID modes: `PASS: runtime exports, level-0 stored RGB/RGBA PNGs, literal pixels, IEND callback boundary, repeated decode, padding`. </details> Cairo compatibility validation: after reviewing the complete introduced diff `2ecc68bda2642fbd5b4c9fb799bc1da4aa3df191..65fa4e73c96d26721170675076e73e07aa6fe1cf`, I three-way merged that exact #18382 head into the local three-PR validation stack. The resulting local commit is `72659301b8c884f06ff5358831bf59d92e2da9c0` (tree `a9c723b70b0efdcd79db6988a93246b41cdae132`). Rebuilding `guest_cairo_png_tests` and the ten codec runtime targets, then adding `guest_cairo_png` to the focused CTest selection above, passed all 12 checks including `public_headers`. This exercises Cairo's 16-bit floating-point PNG outputs, white `bKGD`, eight image formats, subsurfaces and callback failures with the zlib compressor. The raw and NID PNG probes also passed again against freshly copied, hash-verified rebuilt modules. Cairo changes are confined to the local validation tree; the published PNG compression patch is unchanged. ### Checklist <!-- Rules behind each item: https://github.com/boykopovar/AnyPS5/blob/main/CONTRIBUTING.md --> - [x] Based on current `main`; no other open PR implements the same functions - [x] One topic per PR; follow-ups go in a new PR - [x] No comments in code except [technical debt](https://github.com/boykopovar/AnyPS5/blob/main/docs/dev/CONVENTIONS.md) - [x] Unimplemented paths throw (`NotImplemented_nid_no_patch`); silent stubs are listed under Silent stubs in their library's [technical debt](https://github.com/boykopovar/AnyPS5/tree/main/docs/dev/debt) file - [x] No notes, investigation `.md` files or images added to the repository (attach them to this PR) - [x] New third-party code is a submodule built from source - [x] Generic behaviour, not specific to one title - [x] Depends on: none <!-- #PR, or none --> - [x] Fixes: none <!-- issue it closes as Fixes #N, or none --> - [x] Unblocks: none <!-- title ID and Game bring-up discussion, e.g. PPSA01325 #3232, or none --> - [x] GPUs tested: n/a <!-- for AGC, shader recompiler or VideoOut changes: vendor, model, driver and OS of each GPU the GPU tests ran on; otherwise n/a --> - [x] AI-assisted: yes <!-- yes / no -->
PrivacyOnion commented 2026-11-11 14:58:30 +00:00 (Migrated from github.com)

Imported from boykopovar/AnyPS5. Originally posted by PrivacyOnion on 2026-11-11T14:58:30Z.

Review: CHANGES_REQUESTED


Verified on Linux (Ubuntu 24.04, GCC 13.3, Ninja, Release) against 887c2c6e51:

  • Conventions: tools/check_conventions.py failed; git diff --check clean.
    (pull request): error: [pr-template] Fill in the pull request template: add the '### What' heading of the template
    (pull request): error: [pr-template] Fill in the pull request template: add the '### Tested' heading of the template
    (pull request): error: [pr-template] Fill in the pull request template: add the '### Checklist' heading of the template
    3 findings, 3 errors; GitHub shows at most 10 error annotations, the job summary lists all
    
  • Build: decoder_png, decoder_png_tests, guest_png_enc_tests built cleanly.
  • CTest (decoder_png, guest_png_enc):
    1/2 Test #3914: guest_png_enc ....................   Passed    0.06 sec
    2/2 Test #3910: decoder_png ......................   Passed    0.23 sec
    100% tests passed, 0 tests failed out of 2
    
  • Negative control: with core/Decoder/Png/src/Png.cpp reverted to main and the new tests kept, the suite fails:
    1/2 Test #3914: guest_png_enc ....................Subprocess aborted***Exception:   0.60 sec
    2/2 Test #3910: decoder_png ......................Subprocess aborted***Exception:   0.68 sec
    0% tests passed, 2 tests failed out of 2
    
    Restoring the change makes it pass again.
  • Code reading:
    • core/Decoder/Png/src/Png.cpp: Verified that compressBound(inputSize) correctly allocates sufficient buffer capacity for all zlib compression levels 0 through 9 (including level 0 uncompressed/stored blocks with header and block overhead) and that compress2() return status is strictly checked against Z_OK.
    • core/Decoder/Png/src/Png.cpp: Verified integer overflow and bounds handling, ensuring (rowSize + 1) * height <= INT_MAX and compressedSize <= INT_MAX before casting to std::size_t for IDAT chunk emission.
    • core/Decoder/Png/CMakeLists.txt: Verified that zlibstatic is linked PRIVATE to the static library and that LINKER:--exclude-libs,$<TARGET_FILE_NAME:zlibstatic> is properly forwarded via INTERFACE options on Linux and MinGW, preventing host zlib symbols from leaking into guest PRX dynamic symbol tables.
    • core/Decoder/Png/tests/Png.cpp: Verified StoredRows() and RequireCompressionLevels() across all channel formats (1-4), checking zlib CMF/FLG validation (modulo 31), DEFLATE uncompressed block headers (BTYPE=00), LEN/NLEN bitwise inversion (length ^ inverse == 0xFFFF), Adler-32 verification, and multi-block splitting for row buffers exceeding 65,535 bytes.
    • core/libs/tests/GuestPngEnc.cpp: Verified guest PRX encode integration across compression levels 0-9, verifying level 0 stored IDAT headers ((encoded[offset + 10] & 6) == 0) and byte-exact round-trip decoding against input row buffers.
    • core/libs/prx/libScePngEnc/Export.cpp: Verified that compression_level > 9 is rejected with PNG_ENC_ERROR_INVALID_PARAM (0x80690103) and that exceptions from Decoder::Png::Encode are safely caught and converted to PNG_ENC_ERROR_FATAL (0x80690120).
  • Concerns:
    • AGENTS.md:11: The PR description violates the mandatory AGENTS.md PR body specification and failed the mechanical conventions gate (conventions: { ok: false }). The pull request body stripped the required template from .github/pull_request_template.md, missing all required checkboxes and mandatory sections (Depends on, Fixes, Unblocks, GPUs tested, AI-assisted), and left the Tested section truncated mid-sentence.
  • Note: the AI-assisted checkbox can stay.

Requesting changes for the points above.

<!-- greyfinch-sync:boykopovar/AnyPS5:review:5860745901 --> Imported from [boykopovar/AnyPS5](https://github.com/boykopovar/AnyPS5/pull/18387#pullrequestreview-5860745901). Originally posted by [PrivacyOnion](https://github.com/PrivacyOnion) on 2026-11-11T14:58:30Z. **Review:** CHANGES_REQUESTED --- Verified on Linux (Ubuntu 24.04, GCC 13.3, Ninja, Release) against `887c2c6e51`: - **Conventions**: `tools/check_conventions.py` failed; `git diff --check` clean. ``` (pull request): error: [pr-template] Fill in the pull request template: add the '### What' heading of the template (pull request): error: [pr-template] Fill in the pull request template: add the '### Tested' heading of the template (pull request): error: [pr-template] Fill in the pull request template: add the '### Checklist' heading of the template 3 findings, 3 errors; GitHub shows at most 10 error annotations, the job summary lists all ``` - **Build**: `decoder_png`, `decoder_png_tests`, `guest_png_enc_tests` built cleanly. - **CTest** (`decoder_png`, `guest_png_enc`): ``` 1/2 Test #3914: guest_png_enc .................... Passed 0.06 sec 2/2 Test #3910: decoder_png ...................... Passed 0.23 sec 100% tests passed, 0 tests failed out of 2 ``` - **Negative control**: with `core/Decoder/Png/src/Png.cpp` reverted to `main` and the new tests kept, the suite fails: ``` 1/2 Test #3914: guest_png_enc ....................Subprocess aborted***Exception: 0.60 sec 2/2 Test #3910: decoder_png ......................Subprocess aborted***Exception: 0.68 sec 0% tests passed, 2 tests failed out of 2 ``` Restoring the change makes it pass again. - **Code reading**: - core/Decoder/Png/src/Png.cpp: Verified that compressBound(inputSize) correctly allocates sufficient buffer capacity for all zlib compression levels 0 through 9 (including level 0 uncompressed/stored blocks with header and block overhead) and that compress2() return status is strictly checked against Z_OK. - core/Decoder/Png/src/Png.cpp: Verified integer overflow and bounds handling, ensuring (rowSize + 1) * height <= INT_MAX and compressedSize <= INT_MAX before casting to std::size_t for IDAT chunk emission. - core/Decoder/Png/CMakeLists.txt: Verified that zlibstatic is linked PRIVATE to the static library and that LINKER:--exclude-libs,$<TARGET_FILE_NAME:zlibstatic> is properly forwarded via INTERFACE options on Linux and MinGW, preventing host zlib symbols from leaking into guest PRX dynamic symbol tables. - core/Decoder/Png/tests/Png.cpp: Verified StoredRows() and RequireCompressionLevels() across all channel formats (1-4), checking zlib CMF/FLG validation (modulo 31), DEFLATE uncompressed block headers (BTYPE=00), LEN/NLEN bitwise inversion (length ^ inverse == 0xFFFF), Adler-32 verification, and multi-block splitting for row buffers exceeding 65,535 bytes. - core/libs/tests/GuestPngEnc.cpp: Verified guest PRX encode integration across compression levels 0-9, verifying level 0 stored IDAT headers ((encoded[offset + 10] & 6) == 0) and byte-exact round-trip decoding against input row buffers. - core/libs/prx/libScePngEnc/Export.cpp: Verified that compression_level > 9 is rejected with PNG_ENC_ERROR_INVALID_PARAM (0x80690103) and that exceptions from Decoder::Png::Encode are safely caught and converted to PNG_ENC_ERROR_FATAL (0x80690120). - **Concerns**: - AGENTS.md:11: The PR description violates the mandatory AGENTS.md PR body specification and failed the mechanical conventions gate (`conventions: { ok: false }`). The pull request body stripped the required template from `.github/pull_request_template.md`, missing all required checkboxes and mandatory sections (`Depends on`, `Fixes`, `Unblocks`, `GPUs tested`, `AI-assisted`), and left the `Tested` section truncated mid-sentence. - Note: the AI-assisted checkbox can stay. Requesting changes for the points above.
MarcZX10 commented 2026-11-12 14:25:05 +00:00 (Migrated from github.com)

Imported from boykopovar/AnyPS5. Originally posted by MarcZX10 on 2026-11-12T14:25:05Z.

Review: COMMENTED


Reviewed — no blocking findings

Nothing blocks this; the points below are optional.

What I ran

  • Head 887c2c6e51e6b926a773abaa43e9f15b71af1efc, base main. No merged-preview check.
  • Read description.md, commits.md, manifest.json, files.json and diff.patch from the review folder, then the changed hunks and their neighbouring lines at head with the reader. No build, no test run, no write to the repository.
  • The house sections "Readable reviews", "Standard PR response format" and "Accuracy and evidence" were read from the ruling file.
python3 repo_read.py search "stb_image_write" core
python3 repo_read.py search "Adler32" core/Decoder/Png
python3 repo_read.py cat core/Decoder/Png/src/Png.cpp 1 20
python3 repo_read.py cat core/Decoder/Png/src/Png.cpp 190 260
python3 repo_read.py cat core/Decoder/Png/tests/Png.cpp 1 25
python3 repo_read.py cat core/libs/tests/GuestPngEnc.cpp 96 145

Results

Check Result Note
Changed hunks read at head passed 4 files, changed lines and neighbours
Full text of each file read not run hunks only
Build and CTest not run no build in this review
Author's local tests not run author-reported, same head
Hosted Windows job not run author-reported
Commands and output

The commands are listed under What I ran. The search for stb_image_write returned no matching lines. The search for Adler32 returned five matching lines in core/Decoder/Png/tests/Png.cpp and core/libs/tests/GuestWebKitZlib.cpp.

Findings

Blocking

None.

Non-blocking

None found in the changed hunks.

Checked and consistent with the description:

  • Png::Encode rejects levels outside 0–9 before compress2 is called (core/Decoder/Png/src/Png.cpp:196), so zlib gets a valid level. Level 0 selects stored blocks in zlib.
  • The INT_MAX check runs after compression (core/Decoder/Png/src/Png.cpp:230), where compressedSize holds the real size.
  • The stb writer include and implementation are gone, and no stb_image_write reference is left under core.
  • The decoder test helper Adler32 (core/Decoder/Png/tests/Png.cpp:94) is used by the stored-block check; the check on the first IDAT block header in core/libs/tests/GuestPngEnc.cpp reads inside the chunk extent.

Sources

Not verified

  • No build or test was run here. The local results in the description are the author's, on the same head.
  • The description says the hosted Windows job ran only guest_png_enc. The decoder_png tests and the decoder's level-0 regression rest on the author's local run.
  • The zlib archive is hidden from exports only on the MinGW and Linux branch of core/Decoder/Png/CMakeLists.txt. macOS and MSVC behaviour was not checked, and the author says macOS was not tested.
  • Whether other PNG targets use the same link option was not checked. A search with alternation returned nothing, so it is not evidence either way.
  • The zlib submodule pin was not checked.
  • The full text of the four files was not read; only the changed hunks and their neighbouring lines were.

To get this to a good state

Nothing is required.

<!-- greyfinch-sync:boykopovar/AnyPS5:review:5876081457 --> Imported from [boykopovar/AnyPS5](https://github.com/boykopovar/AnyPS5/pull/18387#pullrequestreview-5876081457). Originally posted by [MarcZX10](https://github.com/MarcZX10) on 2026-11-12T14:25:05Z. **Review:** COMMENTED --- # Reviewed — no blocking findings Nothing blocks this; the points below are optional. ## What I ran - Head `887c2c6e51e6b926a773abaa43e9f15b71af1efc`, base `main`. No merged-preview check. - Read `description.md`, `commits.md`, `manifest.json`, `files.json` and `diff.patch` from the review folder, then the changed hunks and their neighbouring lines at head with the reader. No build, no test run, no write to the repository. - The house sections "Readable reviews", "Standard PR response format" and "Accuracy and evidence" were read from the ruling file. ```sh python3 repo_read.py search "stb_image_write" core python3 repo_read.py search "Adler32" core/Decoder/Png python3 repo_read.py cat core/Decoder/Png/src/Png.cpp 1 20 python3 repo_read.py cat core/Decoder/Png/src/Png.cpp 190 260 python3 repo_read.py cat core/Decoder/Png/tests/Png.cpp 1 25 python3 repo_read.py cat core/libs/tests/GuestPngEnc.cpp 96 145 ``` ## Results | Check | Result | Note | | --- | --- | --- | | Changed hunks read at head | passed | 4 files, changed lines and neighbours | | Full text of each file read | not run | hunks only | | Build and CTest | not run | no build in this review | | Author's local tests | not run | author-reported, same head | | Hosted Windows job | not run | author-reported | <details><summary>Commands and output</summary> The commands are listed under What I ran. The search for `stb_image_write` returned no matching lines. The search for `Adler32` returned five matching lines in `core/Decoder/Png/tests/Png.cpp` and `core/libs/tests/GuestWebKitZlib.cpp`. </details> ## Findings **Blocking** None. **Non-blocking** None found in the changed hunks. Checked and consistent with the description: - `Png::Encode` rejects levels outside 0–9 before `compress2` is called (`core/Decoder/Png/src/Png.cpp:196`), so zlib gets a valid level. Level 0 selects stored blocks in zlib. - The `INT_MAX` check runs after compression (`core/Decoder/Png/src/Png.cpp:230`), where `compressedSize` holds the real size. - The stb writer include and implementation are gone, and no `stb_image_write` reference is left under `core`. - The decoder test helper `Adler32` (`core/Decoder/Png/tests/Png.cpp:94`) is used by the stored-block check; the check on the first IDAT block header in `core/libs/tests/GuestPngEnc.cpp` reads inside the chunk extent. ## Sources - Encoder path: https://github.com/boykopovar/AnyPS5/blob/887c2c6e51e6b926a773abaa43e9f15b71af1efc/core/Decoder/Png/src/Png.cpp#L224-L230 - Link option for the zlib archive: https://github.com/boykopovar/AnyPS5/blob/887c2c6e51e6b926a773abaa43e9f15b71af1efc/core/Decoder/Png/CMakeLists.txt#L9-L13 ## Not verified - No build or test was run here. The local results in the description are the author's, on the same head. - The description says the hosted Windows job ran only `guest_png_enc`. The `decoder_png` tests and the decoder's level-0 regression rest on the author's local run. - The zlib archive is hidden from exports only on the MinGW and Linux branch of `core/Decoder/Png/CMakeLists.txt`. macOS and MSVC behaviour was not checked, and the author says macOS was not tested. - Whether other PNG targets use the same link option was not checked. A search with alternation returned nothing, so it is not evidence either way. - The zlib submodule pin was not checked. - The full text of the four files was not read; only the changed hunks and their neighbouring lines were. ## To get this to a good state Nothing is required.
PrivacyOnion commented 2026-11-15 21:09:37 +00:00 (Migrated from github.com)

Imported from boykopovar/AnyPS5. Originally posted by PrivacyOnion on 2026-11-15T21:09:37Z.

Review: APPROVED


Verified on Linux (Ubuntu 24.04, GCC 13.3, Ninja, Release) against 887c2c6e51:

  • Conventions: tools/check_conventions.py passed; git diff --check clean.
  • Build: decoder_png_tests, guest_png_enc_tests built cleanly.
  • CTest (decoder_png, guest_png_enc):
    1/2 Test #4526: guest_png_enc ....................   Passed    0.14 sec
    2/2 Test #4516: decoder_png ......................   Passed    0.23 sec
    100% tests passed, 0 tests failed out of 2
    
  • Negative control: with core/Decoder/Png/src/Png.cpp reverted to main and the new tests kept, the suite fails:
    1/2 Test #4516: decoder_png ......................Subprocess aborted***Exception:   0.70 sec
    2/2 Test #4526: guest_png_enc ....................Subprocess aborted***Exception:   0.80 sec
    0% tests passed, 2 tests failed out of 2
    
    Restoring the change makes it pass again.
  • Code reading:
    • core/Decoder/Png/src/Png.cpp: Verified that compressBound(inputSize) allocates sufficient buffer capacity for all zlib compression levels 0 through 9 (including level 0 stored blocks) and that compress2 return values != Z_OK and compressedSize > INT_MAX are checked and throw std::runtime_error.
    • core/Decoder/Png/src/Png.cpp: Verified that filtered.size() fits safely in uLong before calling compressBound/compress2 given the upstream dimension and row-size overflow checks in Decoder::Png::Encode, and that STB_IMAGE_WRITE_IMPLEMENTATION is cleanly removed in favor of bundled zlibstatic.
    • core/Decoder/Png/CMakeLists.txt: Verified that zlibstatic is linked PRIVATE to the PNG decoder target and hidden from PRX shared library exports on MinGW and Linux via LINKER:--exclude-libs,$<TARGET_FILE_NAME:zlibstatic>.
    • core/Decoder/Png/tests/Png.cpp: Verified that StoredRows validates the zlib header, stored DEFLATE block BTYPE=00 headers, LEN/NLEN 16-bit complements, Adler32 checksums, and multi-block splitting (>65535 bytes) for compression level 0, and that RequireCompressionLevels tests levels 0 through 9 across 1-4 channels and row filters.
    • core/libs/tests/GuestPngEnc.cpp: Verified that the guest scePngEncEncode test exercises compression_level 0 through 9, inspects the IDAT chunk for a stored DEFLATE block header when level == 0, and confirms round-trip pixel decoding.

Looks Good To Me

<!-- greyfinch-sync:boykopovar/AnyPS5:review:5912946148 --> Imported from [boykopovar/AnyPS5](https://github.com/boykopovar/AnyPS5/pull/18387#pullrequestreview-5912946148). Originally posted by [PrivacyOnion](https://github.com/PrivacyOnion) on 2026-11-15T21:09:37Z. **Review:** APPROVED --- Verified on Linux (Ubuntu 24.04, GCC 13.3, Ninja, Release) against `887c2c6e51`: - **Conventions**: `tools/check_conventions.py` passed; `git diff --check` clean. - **Build**: `decoder_png_tests`, `guest_png_enc_tests` built cleanly. - **CTest** (`decoder_png`, `guest_png_enc`): ``` 1/2 Test #4526: guest_png_enc .................... Passed 0.14 sec 2/2 Test #4516: decoder_png ...................... Passed 0.23 sec 100% tests passed, 0 tests failed out of 2 ``` - **Negative control**: with `core/Decoder/Png/src/Png.cpp` reverted to `main` and the new tests kept, the suite fails: ``` 1/2 Test #4516: decoder_png ......................Subprocess aborted***Exception: 0.70 sec 2/2 Test #4526: guest_png_enc ....................Subprocess aborted***Exception: 0.80 sec 0% tests passed, 2 tests failed out of 2 ``` Restoring the change makes it pass again. - **Code reading**: - core/Decoder/Png/src/Png.cpp: Verified that compressBound(inputSize) allocates sufficient buffer capacity for all zlib compression levels 0 through 9 (including level 0 stored blocks) and that compress2 return values != Z_OK and compressedSize > INT_MAX are checked and throw std::runtime_error. - core/Decoder/Png/src/Png.cpp: Verified that filtered.size() fits safely in uLong before calling compressBound/compress2 given the upstream dimension and row-size overflow checks in Decoder::Png::Encode, and that STB_IMAGE_WRITE_IMPLEMENTATION is cleanly removed in favor of bundled zlibstatic. - core/Decoder/Png/CMakeLists.txt: Verified that zlibstatic is linked PRIVATE to the PNG decoder target and hidden from PRX shared library exports on MinGW and Linux via LINKER:--exclude-libs,$<TARGET_FILE_NAME:zlibstatic>. - core/Decoder/Png/tests/Png.cpp: Verified that StoredRows validates the zlib header, stored DEFLATE block BTYPE=00 headers, LEN/NLEN 16-bit complements, Adler32 checksums, and multi-block splitting (>65535 bytes) for compression level 0, and that RequireCompressionLevels tests levels 0 through 9 across 1-4 channels and row filters. - core/libs/tests/GuestPngEnc.cpp: Verified that the guest scePngEncEncode test exercises compression_level 0 through 9, inspects the IDAT chunk for a stored DEFLATE block header when level == 0, and confirms round-trip pixel decoding. Looks Good To Me
Sign in to join this conversation.
No reviewers
No labels
No milestone
No assignees
1 participant
Notifications
Due date
The due date is invalid or out of range. Please use the format "yyyy-mm-dd".

No due date set.

Reference
boykopovar/AnyPS5!18387
No description provided.