Decode PPI face payloads

This commit is contained in:
2026-06-01 13:35:03 +02:00
parent 10e5d5b5ae
commit 88507df90e
13 changed files with 349 additions and 15 deletions

View File

@@ -0,0 +1,94 @@
#include "assets/image_pixels.h"
#include "assets/image_metadata.h"
#include <limits>
#include <utility>
#define STB_IMAGE_STATIC
#define STB_IMAGE_IMPLEMENTATION
#include <stb/stb_image.h>
namespace pp::assets {
namespace {
[[nodiscard]] pp::foundation::Result<std::size_t> rgba_byte_size(
std::uint32_t width,
std::uint32_t height) noexcept
{
const auto pixels = static_cast<std::uint64_t>(width) * static_cast<std::uint64_t>(height);
constexpr auto channels = 4ULL;
if (pixels > std::numeric_limits<std::uint64_t>::max() / channels) {
return pp::foundation::Result<std::size_t>::failure(
pp::foundation::Status::out_of_range("RGBA byte size overflows"));
}
const auto bytes = pixels * channels;
if (bytes > static_cast<std::uint64_t>(std::numeric_limits<std::size_t>::max())) {
return pp::foundation::Result<std::size_t>::failure(
pp::foundation::Status::out_of_range("RGBA byte size exceeds addressable memory"));
}
return pp::foundation::Result<std::size_t>::success(static_cast<std::size_t>(bytes));
}
}
pp::foundation::Result<Rgba8Image> decode_png_rgba8(std::span<const std::byte> bytes)
{
const auto metadata = parse_png_metadata(bytes);
if (!metadata) {
return pp::foundation::Result<Rgba8Image>::failure(metadata.status());
}
if (bytes.size() > static_cast<std::size_t>(std::numeric_limits<int>::max())) {
return pp::foundation::Result<Rgba8Image>::failure(
pp::foundation::Status::out_of_range("PNG payload is too large for the decoder"));
}
int width = 0;
int height = 0;
int source_components = 0;
auto* decoded = stbi_load_from_memory(
reinterpret_cast<const stbi_uc*>(bytes.data()),
static_cast<int>(bytes.size()),
&width,
&height,
&source_components,
4);
if (decoded == nullptr) {
return pp::foundation::Result<Rgba8Image>::failure(
pp::foundation::Status::invalid_argument("PNG payload could not be decoded"));
}
const auto cleanup = [decoded]() noexcept {
stbi_image_free(decoded);
};
if (width <= 0 || height <= 0
|| static_cast<std::uint32_t>(width) != metadata.value().width
|| static_cast<std::uint32_t>(height) != metadata.value().height) {
cleanup();
return pp::foundation::Result<Rgba8Image>::failure(
pp::foundation::Status::invalid_argument("decoded PNG dimensions are inconsistent"));
}
const auto byte_count = rgba_byte_size(metadata.value().width, metadata.value().height);
if (!byte_count) {
cleanup();
return pp::foundation::Result<Rgba8Image>::failure(byte_count.status());
}
Rgba8Image image {
.width = metadata.value().width,
.height = metadata.value().height,
.pixels = {},
};
image.pixels.assign(decoded, decoded + byte_count.value());
cleanup();
return pp::foundation::Result<Rgba8Image>::success(std::move(image));
}
}