diff --git a/.gitmodules b/.gitmodules index 3c7f04fbe..995853108 100644 --- a/.gitmodules +++ b/.gitmodules @@ -22,3 +22,6 @@ [submodule "3rdparty/freetype"] path = 3rdparty/freetype url = https://github.com/freetype/freetype.git +[submodule "3rdparty/stb"] + path = 3rdparty/stb + url = https://github.com/nothings/stb.git diff --git a/3rdparty/stb b/3rdparty/stb new file mode 160000 index 000000000..2c980bb59 --- /dev/null +++ b/3rdparty/stb @@ -0,0 +1 @@ +Subproject commit 2c980bb59875b0d32144a71867fbdebb2f77cd20 diff --git a/CMakeLists.txt b/CMakeLists.txt index 008b7a847..3751edef8 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -45,5 +45,6 @@ add_subdirectory(3rdparty/freetype EXCLUDE_FROM_ALL) set_target_properties(freetype PROPERTIES POSITION_INDEPENDENT_CODE ON) add_subdirectory(core/shader/recompiler) +add_subdirectory(core/Decoder/Jpeg) add_subdirectory(core/libs) add_subdirectory(core/relinker) diff --git a/core/Decoder/Jpeg/CMakeLists.txt b/core/Decoder/Jpeg/CMakeLists.txt new file mode 100644 index 000000000..e438f197a --- /dev/null +++ b/core/Decoder/Jpeg/CMakeLists.txt @@ -0,0 +1,15 @@ +add_library(decoder_jpeg STATIC ${CMAKE_CURRENT_SOURCE_DIR}/src/Jpeg.cpp) +target_include_directories(decoder_jpeg PUBLIC ${CMAKE_CURRENT_SOURCE_DIR}/include) +target_include_directories(decoder_jpeg SYSTEM PRIVATE ${PROJECT_SOURCE_DIR}/3rdparty/stb) +set_target_properties(decoder_jpeg PROPERTIES + CXX_EXTENSIONS OFF + CXX_VISIBILITY_PRESET hidden + VISIBILITY_INLINES_HIDDEN ON + POSITION_INDEPENDENT_CODE ON +) + +if(BUILD_TESTING) + add_executable(decoder_jpeg_tests ${CMAKE_CURRENT_SOURCE_DIR}/tests/Jpeg.cpp) + target_link_libraries(decoder_jpeg_tests PRIVATE decoder_jpeg) + add_test(NAME decoder_jpeg COMMAND decoder_jpeg_tests) +endif() diff --git a/core/Decoder/Jpeg/include/Decoder/Jpeg.hpp b/core/Decoder/Jpeg/include/Decoder/Jpeg.hpp new file mode 100644 index 000000000..330aaeb77 --- /dev/null +++ b/core/Decoder/Jpeg/include/Decoder/Jpeg.hpp @@ -0,0 +1,25 @@ +#ifndef DECODER_JPEG_HPP +#define DECODER_JPEG_HPP + +#include +#include +#include +#include + +namespace Decoder::Jpeg { + +struct Image { + std::uint32_t width; + std::uint32_t height; + std::uint32_t channels; + std::vector pixels; +}; + +std::vector Encode(std::span pixels, std::uint32_t width, std::uint32_t height, + std::uint32_t channels, int quality); + +std::optional Decode(std::span jpeg); + +} // namespace Decoder::Jpeg + +#endif // DECODER_JPEG_HPP diff --git a/core/Decoder/Jpeg/src/Jpeg.cpp b/core/Decoder/Jpeg/src/Jpeg.cpp new file mode 100644 index 000000000..c9f71a731 --- /dev/null +++ b/core/Decoder/Jpeg/src/Jpeg.cpp @@ -0,0 +1,65 @@ +#include "Decoder/Jpeg.hpp" + +#include +#include +#include + +#define STB_IMAGE_WRITE_STATIC +#define STB_IMAGE_WRITE_IMPLEMENTATION +#define STBI_WRITE_NO_STDIO +#include "stb_image_write.h" + +#define STB_IMAGE_STATIC +#define STB_IMAGE_IMPLEMENTATION +#define STBI_ONLY_JPEG +#define STBI_NO_STDIO +#include "stb_image.h" + +namespace Decoder::Jpeg { + +namespace { + +constexpr std::uint32_t MAX_DIMENSION = 0xFFFF; + +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); +} + +} // namespace + +std::vector Encode(std::span pixels, std::uint32_t width, std::uint32_t height, + std::uint32_t channels, int quality) { + if (width == 0 || height == 0 || width > MAX_DIMENSION || height > MAX_DIMENSION) { + throw std::invalid_argument("Jpeg::Encode: unsupported image size"); + } + if (channels != 1 && channels != 3) throw std::invalid_argument("Jpeg::Encode: channels must be 1 or 3"); + if (quality < 1 || quality > 100) throw std::invalid_argument("Jpeg::Encode: quality must be 1-100"); + if (pixels.size() < static_cast(width) * height * channels) { + throw std::invalid_argument("Jpeg::Encode: pixel buffer is too small"); + } + + std::vector output; + const int written = stbi_write_jpg_to_func(appendBytes, &output, static_cast(width), static_cast(height), + static_cast(channels), pixels.data(), quality); + if (written == 0) throw std::runtime_error("Jpeg::Encode: encoding failed"); + return output; +} + +std::optional Decode(std::span jpeg) { + if (jpeg.empty() || jpeg.size() > INT_MAX) return std::nullopt; + + int width = 0; + int height = 0; + int channels = 0; + stbi_uc* decoded = stbi_load_from_memory(jpeg.data(), static_cast(jpeg.size()), &width, &height, &channels, 0); + if (!decoded) return std::nullopt; + + Image image{static_cast(width), static_cast(height), static_cast(channels), {}}; + image.pixels.assign(decoded, decoded + static_cast(image.width) * image.height * image.channels); + stbi_image_free(decoded); + return image; +} + +} // namespace Decoder::Jpeg diff --git a/core/Decoder/Jpeg/tests/Jpeg.cpp b/core/Decoder/Jpeg/tests/Jpeg.cpp new file mode 100644 index 000000000..38e2aa42d --- /dev/null +++ b/core/Decoder/Jpeg/tests/Jpeg.cpp @@ -0,0 +1,77 @@ +#include "Decoder/Jpeg.hpp" + +#include +#include +#include +#include + +static void Require(bool value) { if (!value) std::abort(); } + +template +static bool ThrowsInvalidArgument(TFunction function) { + try { + function(); + } catch (const std::invalid_argument&) { + return true; + } + return false; +} + +static bool IsJpeg(const std::vector& data) { + return data.size() > 4 && data[0] == 0xFF && data[1] == 0xD8 && data[data.size() - 2] == 0xFF && data.back() == 0xD9; +} + +static int Difference(std::uint8_t left, std::uint8_t right) { + return left > right ? left - right : right - left; +} + +int main() { + constexpr std::uint32_t width = 32; + constexpr std::uint32_t height = 24; + + std::vector rgb(width * height * 3); + for (std::uint32_t y = 0; y < height; ++y) { + for (std::uint32_t x = 0; x < width; ++x) { + std::uint8_t* pixel = &rgb[(y * width + x) * 3]; + pixel[0] = static_cast(x * 8); + pixel[1] = static_cast(y * 10); + pixel[2] = 128; + } + } + + const std::vector rgbJpeg = Decoder::Jpeg::Encode(rgb, width, height, 3, 90); + Require(IsJpeg(rgbJpeg)); + const auto rgbImage = Decoder::Jpeg::Decode(rgbJpeg); + Require(rgbImage.has_value()); + Require(rgbImage->width == width && rgbImage->height == height && rgbImage->channels == 3); + Require(rgbImage->pixels.size() == rgb.size()); + long totalError = 0; + for (std::size_t i = 0; i < rgb.size(); ++i) totalError += Difference(rgb[i], rgbImage->pixels[i]); + Require(totalError / static_cast(rgb.size()) < 4); + + std::vector gray(width * height); + for (std::uint32_t y = 0; y < height; ++y) { + for (std::uint32_t x = 0; x < width; ++x) gray[y * width + x] = static_cast((x + y) * 4); + } + const std::vector grayJpeg = Decoder::Jpeg::Encode(gray, width, height, 1, 90); + Require(IsJpeg(grayJpeg)); + const auto grayImage = Decoder::Jpeg::Decode(grayJpeg); + Require(grayImage.has_value()); + Require(grayImage->width == width && grayImage->height == height); + totalError = 0; + for (std::size_t i = 0; i < gray.size(); ++i) totalError += Difference(gray[i], grayImage->pixels[i * grayImage->channels]); + Require(totalError / static_cast(gray.size()) < 4); + + Require(ThrowsInvalidArgument([&] { Decoder::Jpeg::Encode(rgb, width, height, 4, 90); })); + Require(ThrowsInvalidArgument([&] { Decoder::Jpeg::Encode(rgb, width, height, 3, 0); })); + Require(ThrowsInvalidArgument([&] { Decoder::Jpeg::Encode(rgb, width, height, 3, 101); })); + Require(ThrowsInvalidArgument([&] { Decoder::Jpeg::Encode(rgb, 0, height, 3, 90); })); + Require(ThrowsInvalidArgument([&] { Decoder::Jpeg::Encode(rgb, 0x10000, 1, 3, 90); })); + Require(ThrowsInvalidArgument([&] { Decoder::Jpeg::Encode(rgb, width, height + 1, 3, 90); })); + + Require(!Decoder::Jpeg::Decode({}).has_value()); + const std::vector garbage{1, 2, 3, 4, 5, 6, 7, 8}; + Require(!Decoder::Jpeg::Decode(garbage).has_value()); + + return 0; +} diff --git a/core/libs/CMakeLists.txt b/core/libs/CMakeLists.txt index 1fd9ab219..1108074b9 100644 --- a/core/libs/CMakeLists.txt +++ b/core/libs/CMakeLists.txt @@ -407,6 +407,15 @@ if(BUILD_TESTING) set_tests_properties(guest_rtc PROPERTIES ENVIRONMENT_MODIFICATION "PATH=path_list_prepend:$") endif() + add_executable(guest_jpeg_enc_tests tests/GuestJpegEnc.cpp) + target_include_directories(guest_jpeg_enc_tests PRIVATE ${CMAKE_CURRENT_SOURCE_DIR}) + target_link_libraries(guest_jpeg_enc_tests PRIVATE libSceJpegEnc decoder_jpeg libc) + configure_windows_unwind(guest_jpeg_enc_tests) + add_test(NAME guest_jpeg_enc COMMAND guest_jpeg_enc_tests) + if(WIN32) + set_tests_properties(guest_jpeg_enc PROPERTIES ENVIRONMENT_MODIFICATION + "PATH=path_list_prepend:$") + endif() add_executable(guest_font_tests tests/GuestFont.cpp) target_include_directories(guest_font_tests PRIVATE ${CMAKE_CURRENT_SOURCE_DIR}) target_link_libraries(guest_font_tests PRIVATE libSceFont libSceFontFt libc) diff --git a/core/libs/SceTypes.hpp b/core/libs/SceTypes.hpp index 66416b803..50971c093 100644 --- a/core/libs/SceTypes.hpp +++ b/core/libs/SceTypes.hpp @@ -1512,6 +1512,32 @@ struct PngDecImageInfo { std::uint32_t image_flag; }; +struct JpegEncCreateParam { + std::uint32_t size; + std::uint32_t attr; +}; + +struct JpegEncEncodeParam { + const void* image; + void* jpeg; + std::uint32_t image_size; + std::uint32_t jpeg_size; + std::uint32_t image_width; + std::uint32_t image_height; + std::uint32_t image_pitch; + std::uint16_t pixel_format; + std::uint16_t encode_mode; + std::uint16_t color_space; + std::uint8_t sampling_type; + std::uint8_t compression_ratio; + std::int32_t restart_interval; +}; + +struct JpegEncOutputInfo { + std::uint32_t size; + std::uint32_t height; +}; + struct PlayGoInitParams { const void* buf_addr; std::uint32_t buf_size; diff --git a/core/libs/prx/libSceJpegEnc/CMakeLists.txt b/core/libs/prx/libSceJpegEnc/CMakeLists.txt new file mode 100644 index 000000000..4ddeab93a --- /dev/null +++ b/core/libs/prx/libSceJpegEnc/CMakeLists.txt @@ -0,0 +1,5 @@ +add_library(libSceJpegEnc SHARED EXCLUDE_FROM_ALL ${CMAKE_CURRENT_SOURCE_DIR}/Export.cpp) +target_include_directories(libSceJpegEnc PRIVATE ${LIBS_INCLUDE_DIR}) +set_target_properties(libSceJpegEnc PROPERTIES CXX_EXTENSIONS OFF) +configure_windows_unwind(libSceJpegEnc) +target_link_libraries(libSceJpegEnc PRIVATE decoder_jpeg) diff --git a/core/libs/prx/libSceJpegEnc/Export.cpp b/core/libs/prx/libSceJpegEnc/Export.cpp index 8f4b5a78f..d52ad86ac 100644 --- a/core/libs/prx/libSceJpegEnc/Export.cpp +++ b/core/libs/prx/libSceJpegEnc/Export.cpp @@ -1,28 +1,207 @@ +#include #include #include +#include +#include +#include +#include +#include "Decoder/Jpeg.hpp" #include "SceTypes.hpp" -#include "prx/libc/include/General.hpp" + +static_assert(sizeof(JpegEncCreateParam) == 0x8); +static_assert(sizeof(JpegEncEncodeParam) == 0x30); +static_assert(sizeof(JpegEncOutputInfo) == 0x8); + +namespace { + +constexpr std::int32_t SCE_JPEG_ENC_ERROR_INVALID_ADDR = static_cast(0x80650101); +constexpr std::int32_t SCE_JPEG_ENC_ERROR_INVALID_SIZE = static_cast(0x80650102); +constexpr std::int32_t SCE_JPEG_ENC_ERROR_INVALID_PARAM = static_cast(0x80650103); +constexpr std::int32_t SCE_JPEG_ENC_ERROR_INVALID_HANDLE = static_cast(0x80650104); + +constexpr std::uint32_t ATTRIBUTE_NONE = 0; +constexpr std::uint32_t MEMORY_SIZE = 0x800; +constexpr std::uintptr_t HANDLE_ALIGNMENT = 0x20; + +constexpr std::uint16_t PIXEL_FORMAT_R8G8B8A8 = 0; +constexpr std::uint16_t PIXEL_FORMAT_B8G8R8A8 = 1; +constexpr std::uint16_t PIXEL_FORMAT_Y8U8Y8V8 = 10; +constexpr std::uint16_t PIXEL_FORMAT_Y8 = 11; + +constexpr std::uint16_t ENCODE_MODE_NORMAL = 0; +constexpr std::uint16_t ENCODE_MODE_MJPEG = 1; + +constexpr std::uint16_t COLOR_SPACE_YCC = 1; +constexpr std::uint16_t COLOR_SPACE_GRAYSCALE = 2; + +constexpr std::uint8_t SAMPLING_TYPE_FULL = 0; +constexpr std::uint8_t SAMPLING_TYPE_422 = 1; +constexpr std::uint8_t SAMPLING_TYPE_420 = 2; + +constexpr std::uint32_t MAX_IMAGE_DIMENSION = 0xFFFF; +constexpr std::uint32_t MAX_IMAGE_PITCH = 0xFFFFFFF; +constexpr std::uint64_t MAX_IMAGE_SIZE = 0x7FFFFFFF; +constexpr int SUBSAMPLED_MAX_QUALITY = 90; + +struct Encoder { + Encoder* self; +}; + +std::int32_t validateCreateParam(const JpegEncCreateParam* param) { + if (!param) return SCE_JPEG_ENC_ERROR_INVALID_ADDR; + if (param->size != sizeof(JpegEncCreateParam)) return SCE_JPEG_ENC_ERROR_INVALID_SIZE; + if (param->attr != ATTRIBUTE_NONE) return SCE_JPEG_ENC_ERROR_INVALID_PARAM; + return 0; +} + +Encoder* toEncoder(void* handle) { + const auto address = reinterpret_cast(handle); + if (address == 0 || address % HANDLE_ALIGNMENT != 0) return nullptr; + auto* encoder = reinterpret_cast(handle); + return encoder->self == encoder ? encoder : nullptr; +} + +std::int32_t validateEncodeParam(const JpegEncEncodeParam* param) { + if (!param) return SCE_JPEG_ENC_ERROR_INVALID_ADDR; + const bool grayscaleInput = param->pixel_format == PIXEL_FORMAT_Y8; + if (!param->image) return SCE_JPEG_ENC_ERROR_INVALID_ADDR; + if (!grayscaleInput && reinterpret_cast(param->image) % 4 != 0) return SCE_JPEG_ENC_ERROR_INVALID_ADDR; + if (!param->jpeg) return SCE_JPEG_ENC_ERROR_INVALID_ADDR; + + if (param->image_size == 0 || param->jpeg_size == 0) return SCE_JPEG_ENC_ERROR_INVALID_SIZE; + + if (param->image_width == 0 || param->image_height == 0) return SCE_JPEG_ENC_ERROR_INVALID_PARAM; + if (param->image_width > MAX_IMAGE_DIMENSION || param->image_height > MAX_IMAGE_DIMENSION) return SCE_JPEG_ENC_ERROR_INVALID_PARAM; + if (param->image_pitch == 0 || param->image_pitch > MAX_IMAGE_PITCH) return SCE_JPEG_ENC_ERROR_INVALID_PARAM; + if (!grayscaleInput && param->image_pitch % 4 != 0) return SCE_JPEG_ENC_ERROR_INVALID_PARAM; + const std::uint64_t requiredSize = static_cast(param->image_height) * param->image_pitch; + if (requiredSize > MAX_IMAGE_SIZE || requiredSize > param->image_size) return SCE_JPEG_ENC_ERROR_INVALID_PARAM; + if (param->encode_mode != ENCODE_MODE_NORMAL && param->encode_mode != ENCODE_MODE_MJPEG) return SCE_JPEG_ENC_ERROR_INVALID_PARAM; + if (param->color_space != COLOR_SPACE_YCC && param->color_space != COLOR_SPACE_GRAYSCALE) return SCE_JPEG_ENC_ERROR_INVALID_PARAM; + if (param->sampling_type != SAMPLING_TYPE_FULL && param->sampling_type != SAMPLING_TYPE_422 && param->sampling_type != SAMPLING_TYPE_420) { + return SCE_JPEG_ENC_ERROR_INVALID_PARAM; + } + if (param->restart_interval > static_cast(MAX_IMAGE_DIMENSION)) return SCE_JPEG_ENC_ERROR_INVALID_PARAM; + + switch (param->pixel_format) { + case PIXEL_FORMAT_R8G8B8A8: + case PIXEL_FORMAT_B8G8R8A8: + if (param->image_pitch / 4 < param->image_width) return SCE_JPEG_ENC_ERROR_INVALID_PARAM; + if (param->color_space != COLOR_SPACE_YCC || param->sampling_type == SAMPLING_TYPE_FULL) return SCE_JPEG_ENC_ERROR_INVALID_PARAM; + return 0; + case PIXEL_FORMAT_Y8U8Y8V8: + if (param->image_pitch / 2 < ((param->image_width + 1) & ~1u)) return SCE_JPEG_ENC_ERROR_INVALID_PARAM; + if (param->color_space != COLOR_SPACE_YCC || param->sampling_type == SAMPLING_TYPE_FULL) return SCE_JPEG_ENC_ERROR_INVALID_PARAM; + return 0; + case PIXEL_FORMAT_Y8: + if (param->image_pitch < param->image_width) return SCE_JPEG_ENC_ERROR_INVALID_PARAM; + if (param->color_space != COLOR_SPACE_GRAYSCALE || param->sampling_type != SAMPLING_TYPE_FULL) return SCE_JPEG_ENC_ERROR_INVALID_PARAM; + return 0; + default: + return SCE_JPEG_ENC_ERROR_INVALID_PARAM; + } +} + +std::uint8_t clampToByte(float value) { + return static_cast(std::clamp(value + 0.5f, 0.0f, 255.0f)); +} + +void yuvToRgb(std::uint8_t y, std::uint8_t u, std::uint8_t v, std::uint8_t* rgb) { + const float cb = static_cast(u) - 128.0f; + const float cr = static_cast(v) - 128.0f; + rgb[0] = clampToByte(y + 1.402f * cr); + rgb[1] = clampToByte(y - 0.344136f * cb - 0.714136f * cr); + rgb[2] = clampToByte(y + 1.772f * cb); +} + +std::vector toPackedPixels(const JpegEncEncodeParam& param, std::uint32_t channels) { + const auto* image = static_cast(param.image); + const std::size_t width = param.image_width; + std::vector pixels(width * param.image_height * channels); + for (std::size_t y = 0; y < param.image_height; ++y) { + const std::uint8_t* row = image + y * param.image_pitch; + std::uint8_t* out = pixels.data() + y * width * channels; + for (std::size_t x = 0; x < width; ++x) { + switch (param.pixel_format) { + case PIXEL_FORMAT_R8G8B8A8: + out[x * 3 + 0] = row[x * 4 + 0]; + out[x * 3 + 1] = row[x * 4 + 1]; + out[x * 3 + 2] = row[x * 4 + 2]; + break; + case PIXEL_FORMAT_B8G8R8A8: + out[x * 3 + 0] = row[x * 4 + 2]; + out[x * 3 + 1] = row[x * 4 + 1]; + out[x * 3 + 2] = row[x * 4 + 0]; + break; + case PIXEL_FORMAT_Y8U8Y8V8: { + const std::uint8_t* pair = row + (x / 2) * 4; + yuvToRgb(pair[(x % 2) * 2], pair[1], pair[3], out + x * 3); + break; + } + default: + out[x] = row[x]; + break; + } + } + } + return pixels; +} + +int toQuality(const JpegEncEncodeParam& param) { + int quality = 100 - param.compression_ratio * 99 / 255; + if (param.sampling_type != SAMPLING_TYPE_FULL) quality = std::min(quality, SUBSAMPLED_MAX_QUALITY); + return quality; +} + +} // namespace extern "C" { -int APS5_VABI sceJpegEncCreate() { - NotImplemented_nid_no_patch(__func__); - return 0; +int32_t APS5_VABI sceJpegEncCreate(const JpegEncCreateParam* param, void* memory, uint32_t memory_size, void** handle) { + const std::int32_t result = validateCreateParam(param); + if (result != 0) return result; + if (!memory) return SCE_JPEG_ENC_ERROR_INVALID_ADDR; + if (memory_size < MEMORY_SIZE) return SCE_JPEG_ENC_ERROR_INVALID_SIZE; + if (!handle) return SCE_JPEG_ENC_ERROR_INVALID_ADDR; + const auto address = reinterpret_cast(memory); + const std::uintptr_t aligned = (address + HANDLE_ALIGNMENT - 1) & ~(HANDLE_ALIGNMENT - 1); + auto* encoder = new (reinterpret_cast(aligned)) Encoder{}; + encoder->self = encoder; + *handle = encoder; + return 0; } -int APS5_VABI sceJpegEncDelete() { - NotImplemented_nid_no_patch(__func__); - return 0; +int32_t APS5_VABI sceJpegEncDelete(void* handle) { + Encoder* encoder = toEncoder(handle); + if (!encoder) return SCE_JPEG_ENC_ERROR_INVALID_HANDLE; + encoder->self = nullptr; + return 0; } -int APS5_VABI sceJpegEncEncode() { - NotImplemented_nid_no_patch(__func__); - return 0; +int32_t APS5_VABI sceJpegEncEncode(void* handle, const JpegEncEncodeParam* param, JpegEncOutputInfo* output_info) { + if (!toEncoder(handle)) return SCE_JPEG_ENC_ERROR_INVALID_HANDLE; + const std::int32_t result = validateEncodeParam(param); + if (result != 0) return result; + if (param->encode_mode == ENCODE_MODE_MJPEG) throw std::runtime_error("sceJpegEncEncode: MJPEG encode mode is not implemented"); + if (param->restart_interval > 0) throw std::runtime_error("sceJpegEncEncode: restart interval is not implemented"); + + const std::uint32_t channels = param->pixel_format == PIXEL_FORMAT_Y8 ? 1 : 3; + const std::vector pixels = toPackedPixels(*param, channels); + const std::vector jpeg = Decoder::Jpeg::Encode(pixels, param->image_width, param->image_height, channels, toQuality(*param)); + if (jpeg.size() > param->jpeg_size) return SCE_JPEG_ENC_ERROR_INVALID_SIZE; + + std::memcpy(param->jpeg, jpeg.data(), jpeg.size()); + if (output_info) { + output_info->size = static_cast(jpeg.size()); + output_info->height = param->image_height; + } + return 0; } -int APS5_VABI sceJpegEncQueryMemorySize() { - NotImplemented_nid_no_patch(__func__); - return 0; +int32_t APS5_VABI sceJpegEncQueryMemorySize(const JpegEncCreateParam* param) { + const std::int32_t result = validateCreateParam(param); + if (result != 0) return result; + return static_cast(MEMORY_SIZE); } } diff --git a/core/libs/tests/GuestJpegEnc.cpp b/core/libs/tests/GuestJpegEnc.cpp new file mode 100644 index 000000000..7f5983747 --- /dev/null +++ b/core/libs/tests/GuestJpegEnc.cpp @@ -0,0 +1,236 @@ +#include "SceTypes.hpp" +#include "prx/libc/include/general/VabiMacros.hpp" +#include "Decoder/Jpeg.hpp" +#include +#include +#include +#include +#include + +extern "C" { +std::int32_t APS5_VABI sceJpegEncQueryMemorySize(const JpegEncCreateParam*); +std::int32_t APS5_VABI sceJpegEncCreate(const JpegEncCreateParam*, void*, std::uint32_t, void**); +std::int32_t APS5_VABI sceJpegEncDelete(void*); +std::int32_t APS5_VABI sceJpegEncEncode(void*, const JpegEncEncodeParam*, JpegEncOutputInfo*); +} + +static void Require(bool value) { if (!value) std::abort(); } + +alignas(4) static unsigned char image[16 * 16 * 4]; +static unsigned char jpeg[4096]; + +static bool IsJpeg(const unsigned char* data, std::uint32_t size) { + return size > 4 && data[0] == 0xFF && data[1] == 0xD8 && data[size - 2] == 0xFF && data[size - 1] == 0xD9; +} + +static int AverageError(const std::vector& expected, const std::vector& actual) { + long total = 0; + for (std::size_t i = 0; i < expected.size(); ++i) total += expected[i] > actual[i] ? expected[i] - actual[i] : actual[i] - expected[i]; + return static_cast(total / static_cast(expected.size())); +} + +static std::vector DecodeOutput(const JpegEncOutputInfo& info) { + Require(IsJpeg(jpeg, info.size)); + const auto decoded = Decoder::Jpeg::Decode({jpeg, info.size}); + Require(decoded.has_value()); + Require(decoded->width == 16 && decoded->height == 16 && decoded->channels == 3); + return decoded->pixels; +} + +template +static bool ThrowsRuntimeError(TFunction function) { + try { + function(); + } catch (const std::runtime_error&) { + return true; + } + return false; +} + +static JpegEncEncodeParam ValidEncodeParam() { + JpegEncEncodeParam param{}; + param.image = image; + param.jpeg = jpeg; + param.image_size = sizeof(image); + param.jpeg_size = sizeof(jpeg); + param.image_width = 16; + param.image_height = 16; + param.image_pitch = 16 * 4; + param.pixel_format = 0; + param.encode_mode = 0; + param.color_space = 1; + param.sampling_type = 2; + param.compression_ratio = 80; + param.restart_interval = 0; + return param; +} + +int main() { + constexpr std::int32_t invalidAddr = static_cast(0x80650101); + constexpr std::int32_t invalidSize = static_cast(0x80650102); + constexpr std::int32_t invalidParam = static_cast(0x80650103); + constexpr std::int32_t invalidHandle = static_cast(0x80650104); + + JpegEncCreateParam param{sizeof(JpegEncCreateParam), 0}; + Require(sceJpegEncQueryMemorySize(¶m) == 0x800); + Require(sceJpegEncQueryMemorySize(nullptr) == invalidAddr); + + JpegEncCreateParam badSize{sizeof(JpegEncCreateParam) - 1, 0}; + Require(sceJpegEncQueryMemorySize(&badSize) == invalidSize); + + JpegEncCreateParam badAttr{sizeof(JpegEncCreateParam), 1}; + Require(sceJpegEncQueryMemorySize(&badAttr) == invalidParam); + + alignas(32) static unsigned char memory[0x800 + 32]; + unsigned char* unaligned = memory + 1; + void* handle = nullptr; + + Require(sceJpegEncCreate(nullptr, unaligned, 0x800, &handle) == invalidAddr); + Require(sceJpegEncCreate(&badSize, unaligned, 0x800, &handle) == invalidSize); + Require(sceJpegEncCreate(&badAttr, unaligned, 0x800, &handle) == invalidParam); + Require(sceJpegEncCreate(¶m, nullptr, 0x800, &handle) == invalidAddr); + Require(sceJpegEncCreate(¶m, unaligned, 0x7FF, &handle) == invalidSize); + Require(sceJpegEncCreate(¶m, unaligned, 0x800, nullptr) == invalidAddr); + Require(handle == nullptr); + + Require(sceJpegEncCreate(¶m, unaligned, 0x800, &handle) == 0); + const auto address = reinterpret_cast(handle); + Require(address % 32 == 0); + Require(address >= reinterpret_cast(unaligned)); + Require(address < reinterpret_cast(unaligned) + 32); + + Require(sceJpegEncDelete(nullptr) == invalidHandle); + Require(sceJpegEncDelete(static_cast(handle) + 1) == invalidHandle); + alignas(32) static unsigned char garbage[64] = {}; + Require(sceJpegEncDelete(garbage) == invalidHandle); + + Require(sceJpegEncDelete(handle) == 0); + Require(sceJpegEncDelete(handle) == invalidHandle); + + JpegEncOutputInfo info{}; + const JpegEncEncodeParam valid = ValidEncodeParam(); + Require(sceJpegEncEncode(handle, &valid, &info) == invalidHandle); + Require(sceJpegEncEncode(nullptr, &valid, &info) == invalidHandle); + + Require(sceJpegEncCreate(¶m, unaligned, 0x800, &handle) == 0); + Require(sceJpegEncEncode(handle, nullptr, &info) == invalidAddr); + + auto encodeWith = [&](auto change) { + JpegEncEncodeParam changed = ValidEncodeParam(); + change(changed); + return sceJpegEncEncode(handle, &changed, &info); + }; + + Require(encodeWith([](JpegEncEncodeParam& p) { p.image = nullptr; }) == invalidAddr); + Require(encodeWith([](JpegEncEncodeParam& p) { p.image = image + 1; }) == invalidAddr); + Require(encodeWith([](JpegEncEncodeParam& p) { p.jpeg = nullptr; }) == invalidAddr); + Require(encodeWith([](JpegEncEncodeParam& p) { p.image_size = 0; }) == invalidSize); + Require(encodeWith([](JpegEncEncodeParam& p) { p.jpeg_size = 0; }) == invalidSize); + Require(encodeWith([](JpegEncEncodeParam& p) { p.image_width = 0x10000; }) == invalidParam); + Require(encodeWith([](JpegEncEncodeParam& p) { p.image_height = 0x10000; }) == invalidParam); + Require(encodeWith([](JpegEncEncodeParam& p) { p.image_pitch = 0; }) == invalidParam); + Require(encodeWith([](JpegEncEncodeParam& p) { p.image_pitch = 66; }) == invalidParam); + Require(encodeWith([](JpegEncEncodeParam& p) { p.image_size = sizeof(image) - 1; }) == invalidParam); + Require(encodeWith([](JpegEncEncodeParam& p) { p.image_height = 0xFFFF; p.image_pitch = 0xFFFFFFC; }) == invalidParam); + Require(encodeWith([](JpegEncEncodeParam& p) { p.encode_mode = 2; }) == invalidParam); + Require(encodeWith([](JpegEncEncodeParam& p) { p.color_space = 0; }) == invalidParam); + Require(encodeWith([](JpegEncEncodeParam& p) { p.sampling_type = 3; }) == invalidParam); + Require(encodeWith([](JpegEncEncodeParam& p) { p.restart_interval = 0x10000; }) == invalidParam); + Require(encodeWith([](JpegEncEncodeParam& p) { p.pixel_format = 2; }) == invalidParam); + Require(encodeWith([](JpegEncEncodeParam& p) { p.image_width = 17; }) == invalidParam); + Require(encodeWith([](JpegEncEncodeParam& p) { p.color_space = 2; }) == invalidParam); + Require(encodeWith([](JpegEncEncodeParam& p) { p.sampling_type = 0; }) == invalidParam); + Require(encodeWith([](JpegEncEncodeParam& p) { p.pixel_format = 10; p.image_width = 33; }) == invalidParam); + Require(encodeWith([](JpegEncEncodeParam& p) { p.pixel_format = 11; p.color_space = 2; p.sampling_type = 0; p.image_width = 65; }) == invalidParam); + Require(encodeWith([](JpegEncEncodeParam& p) { p.pixel_format = 11; p.color_space = 2; p.sampling_type = 2; }) == invalidParam); + Require(encodeWith([](JpegEncEncodeParam& p) { p.pixel_format = 11; p.sampling_type = 0; }) == invalidParam); + + constexpr std::uint32_t pitch = 16 * 4 + 16; + alignas(4) static unsigned char padded[16 * pitch]; + std::vector expected(16 * 16 * 3); + for (std::uint32_t y = 0; y < 16; ++y) { + for (std::uint32_t x = 0; x < 16; ++x) { + const std::uint8_t color[3] = {static_cast(x * 16), static_cast(y * 16), 96}; + unsigned char* pixel = padded + y * pitch + x * 4; + pixel[0] = color[0]; + pixel[1] = color[1]; + pixel[2] = color[2]; + pixel[3] = 255; + for (int c = 0; c < 3; ++c) expected[(y * 16 + x) * 3 + c] = color[c]; + } + for (std::uint32_t x = 16 * 4; x < pitch; ++x) padded[y * pitch + x] = 0xEE; + } + + JpegEncEncodeParam rgba = ValidEncodeParam(); + rgba.image = padded; + rgba.image_size = sizeof(padded); + rgba.image_pitch = pitch; + rgba.compression_ratio = 0; + info = {}; + Require(sceJpegEncEncode(handle, &rgba, &info) == 0); + Require(info.height == 16); + Require(AverageError(expected, DecodeOutput(info)) < 6); + + for (std::uint32_t y = 0; y < 16; ++y) { + for (std::uint32_t x = 0; x < 16; ++x) { + unsigned char* pixel = padded + y * pitch + x * 4; + const unsigned char red = pixel[0]; + pixel[0] = pixel[2]; + pixel[2] = red; + } + } + JpegEncEncodeParam bgra = rgba; + bgra.pixel_format = 1; + info = {}; + Require(sceJpegEncEncode(handle, &bgra, &info) == 0); + Require(AverageError(expected, DecodeOutput(info)) < 6); + + alignas(4) static unsigned char yuyv[16 * 16 * 2]; + for (std::size_t i = 0; i < sizeof(yuyv); i += 4) { + yuyv[i + 0] = 100; + yuyv[i + 1] = 128; + yuyv[i + 2] = 100; + yuyv[i + 3] = 128; + } + JpegEncEncodeParam yuv = ValidEncodeParam(); + yuv.image = yuyv; + yuv.image_size = sizeof(yuyv); + yuv.image_pitch = 16 * 2; + yuv.pixel_format = 10; + info = {}; + Require(sceJpegEncEncode(handle, &yuv, &info) == 0); + Require(AverageError(std::vector(16 * 16 * 3, 100), DecodeOutput(info)) < 3); + + static unsigned char gray[16 * 16]; + std::vector expectedGray(16 * 16 * 3); + for (std::size_t i = 0; i < sizeof(gray); ++i) { + gray[i] = static_cast(((i % 16) + (i / 16)) * 8); + for (int c = 0; c < 3; ++c) expectedGray[i * 3 + c] = gray[i]; + } + JpegEncEncodeParam y8 = ValidEncodeParam(); + y8.image = gray; + y8.image_size = sizeof(gray); + y8.image_pitch = 16; + y8.pixel_format = 11; + y8.color_space = 2; + y8.sampling_type = 0; + info = {}; + Require(sceJpegEncEncode(handle, &y8, &info) == 0); + Require(AverageError(expectedGray, DecodeOutput(info)) < 6); + + std::memset(jpeg, 0, sizeof(jpeg)); + Require(sceJpegEncEncode(handle, &rgba, nullptr) == 0); + Require(jpeg[0] == 0xFF && jpeg[1] == 0xD8); + + JpegEncEncodeParam tooSmall = rgba; + tooSmall.jpeg_size = 16; + Require(sceJpegEncEncode(handle, &tooSmall, &info) == invalidSize); + + Require(encodeWith([](JpegEncEncodeParam& p) { p.image_width = 0; }) == invalidParam); + Require(ThrowsRuntimeError([&] { encodeWith([](JpegEncEncodeParam& p) { p.encode_mode = 1; }); })); + Require(ThrowsRuntimeError([&] { encodeWith([](JpegEncEncodeParam& p) { p.restart_interval = 1; }); })); + + Require(sceJpegEncDelete(handle) == 0); + + return 0; +} diff --git a/docs/dev/TechnicalDebt.md b/docs/dev/TechnicalDebt.md index 8468605e0..25785c9f2 100644 --- a/docs/dev/TechnicalDebt.md +++ b/docs/dev/TechnicalDebt.md @@ -32,6 +32,7 @@ Throughout the project, every function at every stage either **does exactly what - [Shader recompilation](../../core/shader/recompiler/Recompiler.cpp) currently occurs right before it was transferred to Vulkan with caching, but should be moved to the [relinker](../../core/relinker/main.cpp) stage. For this purpose, [shader/recompiler](../../core/shader/recompiler) was written completely independently from [libs/prx](../../core/libs/prx). - The executable file that [relinker](../../core/relinker/elfpatcher/src/windows/WindowsPeWriter.cpp) generates opens the console when launched, which is inconvenient for playability. +- [libSceJpegEnc](../../core/libs/prx/libSceJpegEnc/Export.cpp) encodes 4:2:2 sampling requests with 4:2:0 chroma subsampling, and grayscale requests as a 3-component JPEG with neutral chroma instead of a single-component one: the [JPEG encoder](../../core/Decoder/Jpeg/src/Jpeg.cpp) (stb) only produces 3-component 4:2:0 and 4:4:4 images. - [Relinker](../../core/relinker/elfpatcher/src) doesn't add an icon to the generated executable. This should be done without adding dependencies (only standard). - `--to-intel` does not lower the register form of INSERTQ (`F2 0F 79`) nor MONITORX/MWAITX/CLZERO/RDPRU/MCOMMIT; the [lowering](../../core/relinker/codegen/src/x86/Sse4aLowering.cpp) fails the relink instead. SHA-NI is not substituted. - The length-changing path of the [instruction rewriter](../../core/relinker/codegen/src/x86/X64InstructionRewriter.cpp) is not used by the [converter](../../core/relinker/codegen/src/Amd64OnlyConverter.cpp): it does not adjust VEX/0F38/0F3A RIP-relative operands, data-to-code references (relocations, FDEs, jump tables) or segment sizes, so every substitution keeps the instruction length.