Merge pull request #592 from DotDebian/fix/pngenc-filter-subset

fix(pngenc): restrict adaptive filtering to the requested filter subset
This commit is contained in:
Dean
2026-10-05 14:23:41 +13:00
committed by GitHub
7 changed files with 213 additions and 31 deletions
+1
View File
@@ -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)
+8 -1
View File
@@ -35,9 +35,16 @@ std::optional<Header> ParseHeader(std::span<const std::uint8_t> png);
std::optional<Image> Decode(std::span<const std::uint8_t> 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<std::uint8_t> Encode(std::span<const std::uint8_t> pixels, std::uint32_t width, std::uint32_t height,
+101 -17
View File
@@ -4,7 +4,8 @@
#include <array>
#include <climits>
#include <cstddef>
#include <mutex>
#include <cstdlib>
#include <memory>
#include <stdexcept>
#define STB_IMAGE_WRITE_STATIC
@@ -26,6 +27,17 @@ constexpr std::array<std::uint8_t, 8> 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<std::uint8_t, 5> COLOR_TYPE_BY_CHANNELS = {0, 0, 4, 2, 6};
constexpr std::array<std::uint32_t, 256> CRC_TABLE = [] {
std::array<std::uint32_t, 256> 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<std::uint32_t>(bytes[0]) << 24 | static_cast<std::uint32_t>(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<std::vector<std::uint8_t>*>(context);
const auto* bytes = static_cast<const std::uint8_t*>(data);
output->insert(output->end(), bytes, bytes + size);
void appendBigEndian32(std::vector<std::uint8_t>& output, std::uint32_t value) {
for (int shift = 24; shift >= 0; shift -= 8) output.push_back(static_cast<std::uint8_t>(value >> shift));
}
void appendChunk(std::vector<std::uint8_t>& output, const char* type, std::span<const std::uint8_t> data) {
appendBigEndian32(output, static_cast<std::uint32_t>(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<std::uint8_t>(row[i] - prediction);
cost += filtered[i] < 0x80 ? filtered[i] : 0x100u - filtered[i];
}
return cost;
}
} // namespace
@@ -105,25 +164,50 @@ std::optional<Image> Decode(std::span<const std::uint8_t> png) {
std::vector<std::uint8_t> Encode(std::span<const std::uint8_t> 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<std::uint64_t>(width) * channels > INT_MAX || height > INT_MAX) {
const std::uint64_t rowSize = static_cast<std::uint64_t>(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<std::size_t>(width) * height * channels) {
if (pixels.size() < rowSize * height) {
throw std::invalid_argument("Png::Encode: pixel buffer is too small");
}
std::vector<std::uint8_t> output;
const int stride = static_cast<int>(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<int>(width), static_cast<int>(height),
static_cast<int>(channels), pixels.data(), stride);
if (written == 0) throw std::runtime_error("Png::Encode: encoding failed");
std::vector<std::uint8_t> filtered((rowSize + 1) * height);
std::vector<std::uint8_t> 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<unsigned char, void (*)(unsigned char*)> compressed(
stbi_zlib_compress(filtered.data(), static_cast<int>(filtered.size()), &compressedSize, options.compressionLevel),
[](unsigned char* memory) { STBIW_FREE(memory); });
if (!compressed) throw std::runtime_error("Png::Encode: encoding failed");
std::vector<std::uint8_t> header;
appendBigEndian32(header, width);
appendBigEndian32(header, height);
header.insert(header.end(), {8, COLOR_TYPE_BY_CHANNELS[channels], 0, 0, 0});
std::vector<std::uint8_t> output(SIGNATURE.begin(), SIGNATURE.end());
output.reserve(SIGNATURE.size() + 3 * CHUNK_OVERHEAD + IHDR_SIZE + static_cast<std::size_t>(compressedSize));
appendChunk(output, "IHDR", header);
appendChunk(output, "IDAT", std::span<const std::uint8_t>(compressed.get(), static_cast<std::size_t>(compressedSize)));
appendChunk(output, "IEND", {});
return output;
}
+64 -4
View File
@@ -1,10 +1,17 @@
#include "Decoder/Png.hpp"
#include <algorithm>
#include <cstdint>
#include <cstdlib>
#include <stdexcept>
#include <vector>
#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<typename TFunction>
@@ -84,11 +91,63 @@ static void RequireRoundTrip(std::uint32_t channels, Decoder::Png::ColorType col
}
}
static std::vector<std::uint8_t> RowFilters(const std::vector<std::uint8_t>& png, std::uint32_t height, std::uint32_t rowSize) {
std::vector<std::uint8_t> stream;
for (std::size_t offset = 8; offset + 12 <= png.size();) {
const std::size_t length = static_cast<std::size_t>(png[offset]) << 24 | static_cast<std::size_t>(png[offset + 1]) << 16
| static_cast<std::size_t>(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<const char*>(stream.data()), static_cast<int>(stream.size()), &size);
Require(rows && static_cast<std::size_t>(size) == static_cast<std::size_t>(height) * (rowSize + 1));
std::vector<std::uint8_t> filters;
for (std::uint32_t y = 0; y < height; ++y) filters.push_back(static_cast<std::uint8_t>(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<std::uint8_t> 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<std::uint8_t>(noise >> 16) : static_cast<std::uint8_t>(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<std::uint8_t> 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<std::uint8_t> 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<std::uint8_t> gradient(64 * 64 * 3);
for (std::size_t i = 0; i < gradient.size(); ++i) gradient[i] = static_cast<std::uint8_t>(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);
+10 -8
View File
@@ -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;
}
+28
View File
@@ -1,8 +1,10 @@
#include "SceTypes.hpp"
#include "prx/libc/include/general/VabiMacros.hpp"
#include "Decoder/Png.hpp"
#include <algorithm>
#include <cstdint>
#include <cstdlib>
#include <utility>
#include <vector>
extern "C" {
@@ -84,6 +86,32 @@ int main() {
}
}
constexpr std::uint32_t rowSize = 16 * 4;
std::vector<std::uint8_t> 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<std::uint8_t>(noise >> 16) : static_cast<std::uint8_t>(i / 4 * 8);
}
}
std::copy_n(rows.begin() + 2 * rowSize, rowSize, rows.begin() + 3 * rowSize);
PngEncEncodeParam filtered{rows.data(), png.data(), static_cast<std::uint32_t>(rows.size()), static_cast<std::uint32_t>(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<std::uint8_t>(png.begin(), png.begin() + size);
};
using namespace Decoder::Png;
const std::pair<std::uint16_t, std::uint8_t> 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);
+1 -1
View File
@@ -51,6 +51,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`
@@ -85,6 +86,5 @@ 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.
- [64-bit LDS atomics](../../core/shader/recompiler/SpirvBackend/src/SpirvMemory/SpirvMemoryInstructions.cpp) (`ds_*_u64`, `ds_*_b64`, `ds_*_f64`) read and write the two dwords under a workgroup lock stored after the guest LDS, as LDS is a 32-bit array without 64-bit atomics. They are atomic with respect to each other only: 32-bit accesses to the same dwords issued concurrently are not ordered by the lock. 64-bit GDS atomics throw. `ds_min/max(_rtn)_f64` and `ds_cmpst(_rtn)_f64` follow the NaN and signed-zero rules measured for the f32 forms; the f64 forms were not measured on hardware.