From bfe9bf9af4a7efce71d4a85c2f9f193a17610831 Mon Sep 17 00:00:00 2001 From: DotDebian Date: Mon, 5 Oct 2026 02:08:15 +0200 Subject: [PATCH] fix(pngenc): restrict adaptive filtering to the requested filter subset A filter_type naming a subset of the PNG filters used only the first filter of the mask, because stb's writer is either fully adaptive or forced to one filter. Decoder::Png::Encode now takes the set of allowed filter types, filters the rows and writes the chunks itself, and keeps stb for deflate only. Output for the all-filters and single-filter cases is unchanged. Co-Authored-By: Claude Opus 5.5 --- core/Decoder/Png/CMakeLists.txt | 1 + core/Decoder/Png/include/Decoder/Png.hpp | 9 +- core/Decoder/Png/src/Png.cpp | 118 +++++++++++++++++++---- core/Decoder/Png/tests/Png.cpp | 68 ++++++++++++- core/libs/prx/libScePngEnc/Export.cpp | 18 ++-- core/libs/tests/GuestPngEnc.cpp | 28 ++++++ docs/dev/TechnicalDebt.md | 2 +- 7 files changed, 213 insertions(+), 31 deletions(-) diff --git a/core/Decoder/Png/CMakeLists.txt b/core/Decoder/Png/CMakeLists.txt index 2c4d268b3..6a86166c2 100644 --- a/core/Decoder/Png/CMakeLists.txt +++ b/core/Decoder/Png/CMakeLists.txt @@ -16,6 +16,7 @@ function(add_png_decoder target runtimeTarget) if(BUILD_TESTING) add_test_executable(${target}_tests ${CMAKE_CURRENT_FUNCTION_LIST_DIR}/tests/Png.cpp) + target_include_directories(${target}_tests SYSTEM PRIVATE ${PROJECT_SOURCE_DIR}/3rdparty/stb) target_link_libraries(${target}_tests PRIVATE ${target}) configure_windows_unwind(${target}_tests) add_test(NAME ${target} COMMAND ${target}_tests) diff --git a/core/Decoder/Png/include/Decoder/Png.hpp b/core/Decoder/Png/include/Decoder/Png.hpp index 051b5f230..175341762 100644 --- a/core/Decoder/Png/include/Decoder/Png.hpp +++ b/core/Decoder/Png/include/Decoder/Png.hpp @@ -35,9 +35,16 @@ std::optional
ParseHeader(std::span png); std::optional Decode(std::span png); +inline constexpr std::uint8_t FILTER_NONE = 1 << 0; +inline constexpr std::uint8_t FILTER_SUB = 1 << 1; +inline constexpr std::uint8_t FILTER_UP = 1 << 2; +inline constexpr std::uint8_t FILTER_AVERAGE = 1 << 3; +inline constexpr std::uint8_t FILTER_PAETH = 1 << 4; +inline constexpr std::uint8_t FILTER_ALL = FILTER_NONE | FILTER_SUB | FILTER_UP | FILTER_AVERAGE | FILTER_PAETH; + struct EncodeOptions { int compressionLevel = 8; - int filter = -1; + std::uint8_t filters = FILTER_ALL; }; std::vector Encode(std::span pixels, std::uint32_t width, std::uint32_t height, diff --git a/core/Decoder/Png/src/Png.cpp b/core/Decoder/Png/src/Png.cpp index 7e8d40b8d..d137df164 100644 --- a/core/Decoder/Png/src/Png.cpp +++ b/core/Decoder/Png/src/Png.cpp @@ -4,7 +4,8 @@ #include #include #include -#include +#include +#include #include #define STB_IMAGE_WRITE_STATIC @@ -26,6 +27,17 @@ constexpr std::array SIGNATURE = {0x89, 0x50, 0x4E, 0x47, 0x0D, constexpr std::size_t CHUNK_OVERHEAD = 12; constexpr std::size_t IHDR_SIZE = 13; constexpr std::uint32_t MAX_DIMENSION = 0x7FFFFFFF; +constexpr std::uint8_t FILTER_TYPE_COUNT = 5; +constexpr std::array COLOR_TYPE_BY_CHANNELS = {0, 0, 4, 2, 6}; +constexpr std::array CRC_TABLE = [] { + std::array table{}; + for (std::uint32_t index = 0; index < table.size(); ++index) { + std::uint32_t value = index; + for (int bit = 0; bit < 8; ++bit) value = (value >> 1) ^ ((value & 1) != 0 ? 0xEDB88320u : 0u); + table[index] = value; + } + return table; +}(); std::uint32_t readBigEndian32(const std::uint8_t* bytes) { return static_cast(bytes[0]) << 24 | static_cast(bytes[1]) << 16 @@ -51,10 +63,57 @@ bool isValidFormat(std::uint8_t bitDepth, std::uint8_t colorType) { } } -void appendBytes(void* context, void* data, int size) { - auto* output = static_cast*>(context); - const auto* bytes = static_cast(data); - output->insert(output->end(), bytes, bytes + size); +void appendBigEndian32(std::vector& output, std::uint32_t value) { + for (int shift = 24; shift >= 0; shift -= 8) output.push_back(static_cast(value >> shift)); +} + +void appendChunk(std::vector& output, const char* type, std::span data) { + appendBigEndian32(output, static_cast(data.size())); + const std::size_t checkedFrom = output.size(); + output.insert(output.end(), type, type + 4); + output.insert(output.end(), data.begin(), data.end()); + std::uint32_t crc = 0xFFFFFFFFu; + for (std::size_t i = checkedFrom; i < output.size(); ++i) crc = (crc >> 8) ^ CRC_TABLE[(crc ^ output[i]) & 0xFF]; + appendBigEndian32(output, ~crc); +} + +int paethPredictor(int left, int up, int upLeft) { + const int estimate = left + up - upLeft; + const int leftDistance = std::abs(estimate - left); + const int upDistance = std::abs(estimate - up); + const int upLeftDistance = std::abs(estimate - upLeft); + if (leftDistance <= upDistance && leftDistance <= upLeftDistance) return left; + return upDistance <= upLeftDistance ? up : upLeft; +} + +std::uint64_t filterRow(const std::uint8_t* row, const std::uint8_t* previousRow, std::size_t rowSize, std::size_t pixelSize, + std::uint8_t filterType, std::uint8_t* filtered) { + std::uint64_t cost = 0; + for (std::size_t i = 0; i < rowSize; ++i) { + const int left = i >= pixelSize ? row[i - pixelSize] : 0; + const int up = previousRow ? previousRow[i] : 0; + const int upLeft = previousRow && i >= pixelSize ? previousRow[i - pixelSize] : 0; + int prediction = 0; + switch (filterType) { + case 1: + prediction = left; + break; + case 2: + prediction = up; + break; + case 3: + prediction = (left + up) >> 1; + break; + case 4: + prediction = paethPredictor(left, up, upLeft); + break; + default: + break; + } + filtered[i] = static_cast(row[i] - prediction); + cost += filtered[i] < 0x80 ? filtered[i] : 0x100u - filtered[i]; + } + return cost; } } // namespace @@ -105,25 +164,50 @@ std::optional Decode(std::span png) { std::vector Encode(std::span pixels, std::uint32_t width, std::uint32_t height, std::uint32_t channels, EncodeOptions options) { if (channels < 1 || channels > 4) throw std::invalid_argument("Png::Encode: channels must be 1-4"); - if (options.compressionLevel < 0 || options.compressionLevel > 9 || options.filter < -1 || options.filter > 4) { + if (options.compressionLevel < 0 || options.compressionLevel > 9 || options.filters == 0 || (options.filters & ~FILTER_ALL) != 0) { throw std::invalid_argument("Png::Encode: unsupported options"); } - if (width == 0 || height == 0 || static_cast(width) * channels > INT_MAX || height > INT_MAX) { + const std::uint64_t rowSize = static_cast(width) * channels; + if (width == 0 || height == 0 || rowSize > INT_MAX || (rowSize + 1) * height > INT_MAX) { throw std::invalid_argument("Png::Encode: unsupported image size"); } - if (pixels.size() < static_cast(width) * height * channels) { + if (pixels.size() < rowSize * height) { throw std::invalid_argument("Png::Encode: pixel buffer is too small"); } - std::vector output; - const int stride = static_cast(width * channels); - static std::mutex optionsMutex; - std::lock_guard lock(optionsMutex); - stbi_write_png_compression_level = options.compressionLevel; - stbi_write_force_png_filter = options.filter; - const int written = stbi_write_png_to_func(appendBytes, &output, static_cast(width), static_cast(height), - static_cast(channels), pixels.data(), stride); - if (written == 0) throw std::runtime_error("Png::Encode: encoding failed"); + std::vector filtered((rowSize + 1) * height); + std::vector candidate(rowSize); + for (std::uint32_t y = 0; y < height; ++y) { + const std::uint8_t* row = pixels.data() + rowSize * y; + const std::uint8_t* previousRow = y == 0 ? nullptr : row - rowSize; + std::uint8_t* filteredRow = filtered.data() + (rowSize + 1) * y; + std::uint64_t bestCost = UINT64_MAX; + for (std::uint8_t filterType = 0; filterType < FILTER_TYPE_COUNT; ++filterType) { + if ((options.filters & (1u << filterType)) == 0) continue; + const std::uint64_t cost =filterRow(row, previousRow, rowSize, channels, filterType, candidate.data()); + if (cost >= bestCost) continue; + bestCost = cost; + filteredRow[0] = filterType; + std::copy(candidate.begin(), candidate.end(), filteredRow + 1); + } + } + + int compressedSize = 0; + const std::unique_ptr compressed( + stbi_zlib_compress(filtered.data(), static_cast(filtered.size()), &compressedSize, options.compressionLevel), + [](unsigned char* memory) { STBIW_FREE(memory); }); + if (!compressed) throw std::runtime_error("Png::Encode: encoding failed"); + + std::vector header; + appendBigEndian32(header, width); + appendBigEndian32(header, height); + header.insert(header.end(), {8, COLOR_TYPE_BY_CHANNELS[channels], 0, 0, 0}); + + std::vector output(SIGNATURE.begin(), SIGNATURE.end()); + output.reserve(SIGNATURE.size() + 3 * CHUNK_OVERHEAD + IHDR_SIZE + static_cast(compressedSize)); + appendChunk(output, "IHDR", header); + appendChunk(output, "IDAT", std::span(compressed.get(), static_cast(compressedSize))); + appendChunk(output, "IEND", {}); return output; } diff --git a/core/Decoder/Png/tests/Png.cpp b/core/Decoder/Png/tests/Png.cpp index 9129f03dc..7287ed5b3 100644 --- a/core/Decoder/Png/tests/Png.cpp +++ b/core/Decoder/Png/tests/Png.cpp @@ -1,10 +1,17 @@ #include "Decoder/Png.hpp" +#include #include #include #include #include +#define STB_IMAGE_STATIC +#define STB_IMAGE_IMPLEMENTATION +#define STBI_ONLY_PNG +#define STBI_NO_STDIO +#include "stb_image.h" + static void Require(bool value) { if (!value) std::abort(); } template @@ -84,11 +91,63 @@ static void RequireRoundTrip(std::uint32_t channels, Decoder::Png::ColorType col } } +static std::vector RowFilters(const std::vector& png, std::uint32_t height, std::uint32_t rowSize) { + std::vector stream; + for (std::size_t offset = 8; offset + 12 <= png.size();) { + const std::size_t length = static_cast(png[offset]) << 24 | static_cast(png[offset + 1]) << 16 + | static_cast(png[offset + 2]) << 8 | png[offset + 3]; + Require(length <= png.size() - offset - 12); + const std::uint8_t* data = png.data() + offset + 8; + if (std::equal(data - 4, data, "IDAT")) stream.insert(stream.end(), data, data + length); + offset += 12 + length; + } + + int size = 0; + char* rows = stbi_zlib_decode_malloc(reinterpret_cast(stream.data()), static_cast(stream.size()), &size); + Require(rows && static_cast(size) == static_cast(height) * (rowSize + 1)); + std::vector filters; + for (std::uint32_t y = 0; y < height; ++y) filters.push_back(static_cast(rows[y * (rowSize + 1)])); + stbi_image_free(rows); + return filters; +} + +static void RequireFilterSets(std::uint32_t channels) { + constexpr std::uint32_t width = 16; + constexpr std::uint32_t height = 6; + const std::uint32_t rowSize = width * channels; + std::vector pixels(rowSize * height); + std::uint32_t noise = 12345; + for (std::uint32_t y = 0; y < height; ++y) { + for (std::uint32_t i = 0; i < rowSize; ++i) { + noise = noise * 1103515245u + 12345u; + pixels[y * rowSize + i] = y == 2 ? static_cast(noise >> 16) : static_cast(i / channels * 8); + } + } + std::copy_n(pixels.begin() + 2 * rowSize, rowSize, pixels.begin() + 3 * rowSize); + + for (std::uint8_t filters = 1; filters <= Decoder::Png::FILTER_ALL; ++filters) { + const std::vector png = Decoder::Png::Encode(pixels, width, height, channels, {6, filters}); + for (const std::uint8_t filter : RowFilters(png, height, rowSize)) Require(filter < 5 && (filters >> filter & 1) != 0); + + const auto image = Decoder::Png::Decode(png); + Require(image.has_value() && image->width == width && image->height == height); + for (std::size_t pixel = 0; pixel < width * height; ++pixel) { + Require(image->pixels[pixel * 4] == pixels[pixel * channels]); + Require(image->pixels[pixel * 4 + 3] == (channels % 2 == 0 ? pixels[pixel * channels + channels - 1] : 255)); + } + } + + const std::vector subOrUp = RowFilters( + Decoder::Png::Encode(pixels, width, height, channels, {6, Decoder::Png::FILTER_SUB | Decoder::Png::FILTER_UP}), height, rowSize); + Require(subOrUp[0] == 1 && subOrUp[1] == 2 && subOrUp[3] == 2 && subOrUp[4] == 1 && subOrUp[5] == 2); +} + int main() { RequireRoundTrip(1, Decoder::Png::ColorType::Grayscale); RequireRoundTrip(2, Decoder::Png::ColorType::GrayscaleAlpha); RequireRoundTrip(3, Decoder::Png::ColorType::Rgb); RequireRoundTrip(4, Decoder::Png::ColorType::Rgba); + for (const std::uint32_t channels : {1, 2, 3, 4}) RequireFilterSets(channels); const auto paletteHeader = Decoder::Png::ParseHeader(PALETTE_TRNS); Require(paletteHeader.has_value()); @@ -140,13 +199,14 @@ int main() { Require(ThrowsInvalidArgument([&] { Decoder::Png::Encode(pixels, 4, 4, 5); })); Require(ThrowsInvalidArgument([&] { Decoder::Png::Encode(pixels, 0, 4, 4); })); Require(ThrowsInvalidArgument([&] { Decoder::Png::Encode(pixels, 4, 5, 4); })); - Require(ThrowsInvalidArgument([&] { Decoder::Png::Encode(pixels, 4, 4, 4, {10, -1}); })); - Require(ThrowsInvalidArgument([&] { Decoder::Png::Encode(pixels, 4, 4, 4, {8, 5}); })); + Require(ThrowsInvalidArgument([&] { Decoder::Png::Encode(pixels, 4, 4, 4, {10, Decoder::Png::FILTER_ALL}); })); + Require(ThrowsInvalidArgument([&] { Decoder::Png::Encode(pixels, 4, 4, 4, {8, 0}); })); + Require(ThrowsInvalidArgument([&] { Decoder::Png::Encode(pixels, 4, 4, 4, {8, Decoder::Png::FILTER_ALL + 1}); })); std::vector gradient(64 * 64 * 3); for (std::size_t i = 0; i < gradient.size(); ++i) gradient[i] = static_cast(i / 3 % 64 * 4); - const auto stored = Decoder::Png::Encode(gradient, 64, 64, 3, {0, 0}); - const auto compressed = Decoder::Png::Encode(gradient, 64, 64, 3, {9, 1}); + const auto stored = Decoder::Png::Encode(gradient, 64, 64, 3, {0, Decoder::Png::FILTER_NONE}); + const auto compressed = Decoder::Png::Encode(gradient, 64, 64, 3, {9, Decoder::Png::FILTER_SUB}); Require(compressed.size() < stored.size()); for (const auto& png : {stored, compressed}) { const auto image = Decoder::Png::Decode(png); diff --git a/core/libs/prx/libScePngEnc/Export.cpp b/core/libs/prx/libScePngEnc/Export.cpp index 11aa6731b..4ff0af04e 100644 --- a/core/libs/prx/libScePngEnc/Export.cpp +++ b/core/libs/prx/libScePngEnc/Export.cpp @@ -52,13 +52,15 @@ PngEncContext* context(void* handle) { return ctx && ctx->magic == CONTEXT_MAGIC ? ctx : nullptr; } -int filterMode(std::uint16_t filterType) { - if (filterType == FILTER_ALL) return -1; - if (filterType & FILTER_SUB) return 1; - if (filterType & FILTER_UP) return 2; - if (filterType & FILTER_AVERAGE) return 3; - if (filterType & FILTER_PAETH) return 4; - return 0; +std::uint8_t filterSet(std::uint16_t filterType) { + if (filterType == FILTER_ALL) return Decoder::Png::FILTER_ALL; + if (filterType == 0) return Decoder::Png::FILTER_NONE; + std::uint8_t filters = 0; + if (filterType & FILTER_SUB) filters |= Decoder::Png::FILTER_SUB; + if (filterType & FILTER_UP) filters |= Decoder::Png::FILTER_UP; + if (filterType & FILTER_AVERAGE) filters |= Decoder::Png::FILTER_AVERAGE; + if (filterType & FILTER_PAETH) filters |= Decoder::Png::FILTER_PAETH; + return filters; } } @@ -120,7 +122,7 @@ int APS5_VABI scePngEncEncode(void* handle, const PngEncEncodeParam* param, PngE if (channels == 4) *destination++ = source[3]; } } - png = Decoder::Png::Encode(pixels, width, height, channels, {param->compression_level, filterMode(param->filter_type)}); + png = Decoder::Png::Encode(pixels, width, height, channels, {param->compression_level, filterSet(param->filter_type)}); } catch (const std::exception&) { return PNG_ENC_ERROR_FATAL; } diff --git a/core/libs/tests/GuestPngEnc.cpp b/core/libs/tests/GuestPngEnc.cpp index 9208ae7f0..7535dae85 100644 --- a/core/libs/tests/GuestPngEnc.cpp +++ b/core/libs/tests/GuestPngEnc.cpp @@ -1,8 +1,10 @@ #include "SceTypes.hpp" #include "prx/libc/include/general/VabiMacros.hpp" #include "Decoder/Png.hpp" +#include #include #include +#include #include extern "C" { @@ -84,6 +86,32 @@ int main() { } } + constexpr std::uint32_t rowSize = 16 * 4; + std::vector rows(rowSize * 6); + std::uint32_t noise = 12345; + for (std::uint32_t y = 0; y < 6; ++y) { + for (std::uint32_t i = 0; i < rowSize; ++i) { + noise = noise * 1103515245u + 12345u; + rows[y * rowSize + i] = y == 2 ? static_cast(noise >> 16) : static_cast(i / 4 * 8); + } + } + std::copy_n(rows.begin() + 2 * rowSize, rowSize, rows.begin() + 3 * rowSize); + PngEncEncodeParam filtered{rows.data(), png.data(), static_cast(rows.size()), static_cast(png.size()), + 16, 6, rowSize, 0, 19, 8, 0, 0, 6}; + const auto encodeWith = [&](std::uint16_t filterType) { + filtered.filter_type = filterType; + const int size = scePngEncEncode(handle, &filtered, nullptr); + Require(size > 0); + return std::vector(png.begin(), png.begin() + size); + }; + using namespace Decoder::Png; + const std::pair filterSets[] = { + {0, FILTER_NONE}, {1, FILTER_SUB}, {2, FILTER_UP}, {4, FILTER_AVERAGE}, {8, FILTER_PAETH}, + {3, FILTER_SUB | FILTER_UP}, {6, FILTER_UP | FILTER_AVERAGE}, {9, FILTER_SUB | FILTER_PAETH}, + {14, FILTER_UP | FILTER_AVERAGE | FILTER_PAETH}, {15, FILTER_ALL}}; + for (const auto& [filterType, filters] : filterSets) Require(encodeWith(filterType) == Encode(rows, 16, 6, 4, {6, filters})); + Require(encodeWith(3) != encodeWith(1) && encodeWith(3) != encodeWith(2) && encodeWith(15) != encodeWith(14)); + encode.png_mem_size = 20; PngEncOutputInfo info{1, 1}; Require(scePngEncEncode(handle, &encode, &info) == dataOverflow && info.data_size == 0 && info.processed_height == 0); diff --git a/docs/dev/TechnicalDebt.md b/docs/dev/TechnicalDebt.md index 5c87a3d98..807f61048 100644 --- a/docs/dev/TechnicalDebt.md +++ b/docs/dev/TechnicalDebt.md @@ -50,6 +50,7 @@ Throughout the project, every function at every stage either **does exactly what - [AOWqIYsgVHs](../../core/libs/prx/libSceContentExport/Export.cpp) (libSceContentExport) - unknown name, signature - [GQTObcITIXI](../../core/libs/prx/libSceShare/Export.cpp) (libSceShare) - unknown name, signature - [BnMAMrsfVWo](../../core/libs/prx/libc/src/HeapDiagnostics.cpp) (libc) - unknown name, signature +- [scePngEncEncode](../../core/libs/prx/libScePngEnc/Export.cpp) (libScePngEnc) - whether rows may stay unfiltered when `filter_type` names a subset of the filters is unknown; as in shadPS4, they may only for 0 and for the all-filters mask - AudioIn, NpSessionSignaling and PlayerInvitationDialog exports added without an implementation have assumed signatures - [libSceAudioPropagation](../../core/libs/prx/libSceAudioPropagation/Export.cpp) (libSceAudioPropagation) - signatures and struct descriptors recovered from PPSA21567's calls (#481), not from documentation. The system options layout is unknown (only checked for non-null); the fourth argument of `sceAudioPropagationSourceCalculateAudioPaths` is unknown; `sceAudioPropagationSourceGetAudioPath` is assumed to output an 8-byte path handle. The meaning of the `RenderInfo` word at +0x28 is unknown (PPSA21567 and PPSA21564 pass 2); only 2 is accepted. Both titles pass one `RenderInfo` per call: a count of 0 throws, and larger counts are handled element by element without proof. No error code is known, so invalid input throws instead of returning one - [sceAvPlayerStartEx](../../core/libs/prx/libSceAvPlayer/Export.cpp) (libSceAvPlayer) - start info layout unknown; it is ignored and playback starts as with `sceAvPlayerStart` @@ -74,5 +75,4 @@ Throughout the project, every function at every stage either **does exactly what - [sceKeyboardGetKey2Char](../../core/libs/prx/libSceKeyboard/src/keyboard_impl.cpp) (libSceKeyboard) translates only the 101-key (US) arrangement and throws for the 106-key (Japanese) one; Ctrl and Alt do not change the character. - [libSceAudiodec](../../core/libs/prx/libSceAudiodec/Export.cpp) throws for the 24-bit PCM word size (`iBwPcm` 0): its sample layout is unknown. ATRAC9 decoding is covered only by configuration and error tests, as no ATRAC9 encoder is available for a fixture. - [sceAjmDecMp3ParseFrame](../../core/libs/prx/libSceAjm.native/src/Ajm.cpp) (libSceAjm.native) throws when the original file length is requested (`parse_ofl` non-zero): reading it from the frame's Xing/Info, VBRI or Fraunhofer data is not implemented. -- [libScePngEnc](../../core/libs/prx/libScePngEnc/Export.cpp) honours `filter_type` only as all filters (adaptive) or a single filter: the [PNG encoder](../../core/Decoder/Png/src/Png.cpp) (stb) cannot restrict adaptive filtering to a subset, so the first filter in the mask is used. - [libScePlayerInvitationDialog](../../core/libs/prx/libScePlayerInvitationDialog/libScePlayerInvitationDialog.cpp) simulates dialog completion without displaying UI or sending invitations; its parameter ABI remains unverified.