From a38ef6132f269fe9a7bd31e14ae62fae88c2e758 Mon Sep 17 00:00:00 2001 From: Pacuka <69674426+Pacuka@users.noreply.github.com> Date: Sun, 27 Sep 2026 21:52:03 +0200 Subject: [PATCH 1/4] feat(videodec2): decode H.264 with FFmpeg Adds libSceVideodec2. Access units (Annex B, or length-prefixed rewritten to Annex B) are decoded by FFmpeg's H.264 decoder into the title's NV12 frame buffers (256-byte pitch, chroma after the visible luma rows). Decode hands out at most one picture per call, Flush drains the reordered ones, Reset clears the decoder; timestamps and attached data travel with the picture. FFmpeg is found through pkg-config and is optional: without it the decoders return black pictures. guest_videodec2_tests checks the pictures of an embedded stream against reference hashes. Co-Authored-By: Claude Opus 5.5 --- core/libs/CMakeLists.txt | 11 + core/libs/prx/libSceVideodec2/CMakeLists.txt | 19 + core/libs/prx/libSceVideodec2/Export.cpp | 623 +++++++++++++++++++ core/libs/tests/GuestVideodec2.cpp | 299 +++++++++ 4 files changed, 952 insertions(+) create mode 100644 core/libs/prx/libSceVideodec2/CMakeLists.txt create mode 100644 core/libs/prx/libSceVideodec2/Export.cpp create mode 100644 core/libs/tests/GuestVideodec2.cpp diff --git a/core/libs/CMakeLists.txt b/core/libs/CMakeLists.txt index f44ae80e3..7c0440810 100644 --- a/core/libs/CMakeLists.txt +++ b/core/libs/CMakeLists.txt @@ -449,6 +449,17 @@ if(BUILD_TESTING) set_tests_properties(fiber PROPERTIES ENVIRONMENT_MODIFICATION "PATH=path_list_prepend:$") endif() + if(VIDEODEC2_HAS_FFMPEG) + add_executable(guest_videodec2_tests tests/GuestVideodec2.cpp) + target_include_directories(guest_videodec2_tests PRIVATE ${CMAKE_CURRENT_SOURCE_DIR}) + target_link_libraries(guest_videodec2_tests PRIVATE libSceVideodec2 libc) + configure_windows_unwind(guest_videodec2_tests) + add_test(NAME guest_videodec2 COMMAND guest_videodec2_tests) + if(WIN32) + set_tests_properties(guest_videodec2 PROPERTIES ENVIRONMENT_MODIFICATION + "PATH=path_list_prepend:$") + endif() + endif() add_executable(mspace_tests tests/Mspace.cpp) target_include_directories(mspace_tests PRIVATE ${CMAKE_CURRENT_SOURCE_DIR}) target_link_libraries(mspace_tests PRIVATE libc) diff --git a/core/libs/prx/libSceVideodec2/CMakeLists.txt b/core/libs/prx/libSceVideodec2/CMakeLists.txt new file mode 100644 index 000000000..65d3b882c --- /dev/null +++ b/core/libs/prx/libSceVideodec2/CMakeLists.txt @@ -0,0 +1,19 @@ +add_library(libSceVideodec2 SHARED EXCLUDE_FROM_ALL + ${CMAKE_CURRENT_SOURCE_DIR}/Export.cpp +) + +target_include_directories(libSceVideodec2 PRIVATE ${LIBS_INCLUDE_DIR}) +configure_windows_unwind(libSceVideodec2) + +find_package(PkgConfig QUIET) +if(PKG_CONFIG_FOUND) + pkg_check_modules(VIDEODEC2_FFMPEG QUIET IMPORTED_TARGET libavcodec libavutil libswscale) +endif() +if(VIDEODEC2_FFMPEG_FOUND) + target_link_libraries(libSceVideodec2 PRIVATE PkgConfig::VIDEODEC2_FFMPEG) + target_compile_definitions(libSceVideodec2 PRIVATE APS5_HAVE_FFMPEG=1) + set(VIDEODEC2_HAS_FFMPEG ON PARENT_SCOPE) + message(STATUS "libSceVideodec2: H.264 decoding with FFmpeg ${VIDEODEC2_FFMPEG_libavcodec_VERSION}") +else() + message(STATUS "libSceVideodec2: FFmpeg not found, decoders return black pictures") +endif() diff --git a/core/libs/prx/libSceVideodec2/Export.cpp b/core/libs/prx/libSceVideodec2/Export.cpp new file mode 100644 index 000000000..10e6d6571 --- /dev/null +++ b/core/libs/prx/libSceVideodec2/Export.cpp @@ -0,0 +1,623 @@ +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include "SceTypes.hpp" +#include "prx/libc/include/General.hpp" + +#if APS5_HAVE_FFMPEG +extern "C" { +#include +#include +#include +#include +} +#endif + +// Tech debt: without FFmpeg (APS5_HAVE_FFMPEG unset) decoders return black NV12 pictures that +// carry the access unit timestamps, so players still advance through a movie. + +namespace { + +constexpr int SCE_VIDEODEC2_ERROR_ARGUMENT_POINTER = static_cast(0x811d0103u); +constexpr int SCE_VIDEODEC2_ERROR_DECODER_INSTANCE = static_cast(0x811d0106u); +constexpr std::uint64_t WorkMemoryBytes = 1u << 20u; +constexpr std::uint32_t PitchAlignment = 256; +constexpr std::uint32_t HeightAlignment = 32; + +struct ComputeMemoryInfo { + std::uint64_t thisSize; + std::uint64_t cpuGpuMemorySize; + void* cpuGpuMemory; +}; + +struct ComputeConfigInfo { + std::uint64_t thisSize; + std::uint16_t computePipeId; + std::uint16_t computeQueueId; + bool checkMemoryType; +}; + +struct DecoderConfigInfo { + std::uint64_t thisSize; + std::uint32_t resourceType; + std::uint32_t codecType; + std::uint32_t profile; + std::uint32_t maxLevel; + std::int32_t maxFrameWidth; + std::int32_t maxFrameHeight; + std::int32_t maxDpbFrameCount; + std::uint32_t decodePipelineDepth; +}; + +struct DecoderMemoryInfo { + std::uint64_t thisSize; + std::uint64_t cpuMemorySize; + void* cpuMemory; + std::uint64_t gpuMemorySize; + void* gpuMemory; + std::uint64_t cpuGpuMemorySize; + void* cpuGpuMemory; + std::uint64_t maxFrameBufferSize; + std::uint32_t frameBufferAlignment; +}; + +struct InputData { + std::uint64_t thisSize; + const std::uint8_t* auData; + std::uint64_t auSize; + std::uint64_t ptsData; + std::uint64_t dtsData; + std::uint64_t attachedData; +}; + +struct FrameBuffer { + std::uint64_t thisSize; + void* frameBuffer; + std::uint64_t frameBufferSize; + bool isAccepted; +}; + +struct OutputInfo { + std::uint64_t thisSize; + bool isValid; + bool isErrorFrame; + std::uint8_t pictureCount; + std::uint32_t codecType; + std::uint32_t frameWidth; + std::uint32_t framePitch; + std::uint32_t frameHeight; + void* frameBuffer; + std::uint64_t frameBufferSize; + std::uint32_t frameFormat; + std::uint32_t framePitchInBytes; +}; + +struct AvcPictureInfo { + std::uint64_t thisSize; + bool isValid; + std::uint64_t ptsData; + std::uint64_t dtsData; + std::uint64_t attachedData; + std::uint8_t idrPictureFlag; + std::uint8_t profileIdc; + std::uint8_t levelIdc; + std::uint32_t picWidthInLumaSamples; + std::uint32_t picHeightInLumaSamples; +}; + +struct Picture { + std::uint64_t pts = 0; + std::uint64_t dts = 0; + std::uint64_t attached = 0; + bool idr = false; +}; + +#if APS5_HAVE_FFMPEG +struct FrameDeleter { + void operator()(AVFrame* frame) const { av_frame_free(&frame); } +}; +using FramePointer = std::unique_ptr; +#endif + +struct Decoder { + std::uint32_t codec = 0; + std::uint32_t width = 0; + std::uint32_t height = 0; + std::uint32_t profile = 0; + std::uint32_t level = 0; + std::map pictures; + std::uint64_t decoded = 0; + std::mutex mutex; +#if APS5_HAVE_FFMPEG + AVCodecContext* context = nullptr; + SwsContext* scaler = nullptr; + std::map inputs; + std::int64_t nextKey = 0; + std::deque ready; + std::vector annexB; + bool flushing = false; + + ~Decoder() { + sws_freeContext(scaler); + avcodec_free_context(&context); + } +#endif +}; + +std::mutex lock; +std::map> decoders; +std::uint64_t nextDecoder = 1; +std::uint64_t nextQueue = 1; + +bool Trace() { + static const bool trace = std::getenv("APS5_TRACE_VIDEODEC") != nullptr; + return trace; +} + +std::uint32_t AlignUp(std::uint32_t value, std::uint32_t alignment) { + return (value + alignment - 1) / alignment * alignment; +} + +std::uint64_t ChromaOffset(std::uint32_t width, std::uint32_t height) { + return static_cast(AlignUp(width, PitchAlignment)) * height; +} + +std::uint64_t LumaBytes(std::uint32_t width, std::uint32_t height) { + return static_cast(AlignUp(width, PitchAlignment)) * AlignUp(height, HeightAlignment); +} + +template +bool Fits(const T* object, std::size_t end) { + return object->thisSize >= end; +} + +class BitReader { +public: + BitReader(const std::uint8_t* data, std::size_t size) : data(data), size(size) {} + + std::uint32_t Bit() { + if (position >= size * 8) { failed = true; return 0; } + const auto bit = (data[position / 8] >> (7 - position % 8)) & 1u; + ++position; + return bit; + } + + std::uint32_t Bits(unsigned count) { + std::uint32_t value = 0; + for (unsigned index = 0; index < count; ++index) value = (value << 1u) | Bit(); + return value; + } + + std::uint32_t Ue() { + unsigned zeros = 0; + while (Bit() == 0 && !failed && zeros < 32) ++zeros; + if (zeros >= 32) { failed = true; return 0; } + return ((1u << zeros) - 1u) + Bits(zeros); + } + + std::int32_t Se() { + const auto value = Ue(); + return (value & 1u) != 0 ? static_cast((value + 1) / 2) : -static_cast(value / 2); + } + + bool failed = false; + +private: + const std::uint8_t* data; + std::size_t size; + std::size_t position = 0; +}; + +void SkipScalingList(BitReader& reader, int count) { + int last = 8; + int next = 8; + for (int index = 0; index < count; ++index) { + if (next != 0) next = (last + reader.Se() + 256) % 256; + last = next == 0 ? last : next; + } +} + +bool ParseSps(const std::uint8_t* nal, std::size_t size, Decoder& decoder) { + std::uint8_t rbsp[256]; + std::size_t length = 0; + for (std::size_t index = 1; index < size && length < sizeof(rbsp); ++index) { + if (index >= 3 && nal[index] == 3 && nal[index - 1] == 0 && nal[index - 2] == 0) continue; + rbsp[length++] = nal[index]; + } + BitReader reader(rbsp, length); + const auto profile = reader.Bits(8); + reader.Bits(8); + const auto level = reader.Bits(8); + reader.Ue(); + std::uint32_t chromaFormat = 1; + if (profile == 100 || profile == 110 || profile == 122 || profile == 244 || profile == 44 || profile == 83 || profile == 86 || profile == 118 || profile == 128) { + chromaFormat = reader.Ue(); + if (chromaFormat == 3) reader.Bit(); + reader.Ue(); + reader.Ue(); + reader.Bit(); + if (reader.Bit() != 0) { + for (int index = 0; index < (chromaFormat != 3 ? 8 : 12); ++index) { + if (reader.Bit() != 0) SkipScalingList(reader, index < 6 ? 16 : 64); + } + } + } + reader.Ue(); + const auto pocType = reader.Ue(); + if (pocType == 0) { + reader.Ue(); + } else if (pocType == 1) { + reader.Bit(); + reader.Se(); + reader.Se(); + const auto cycle = reader.Ue(); + for (std::uint32_t index = 0; index < cycle && !reader.failed; ++index) reader.Se(); + } + reader.Ue(); + reader.Bit(); + const auto widthMbs = reader.Ue() + 1; + const auto heightMapUnits = reader.Ue() + 1; + const auto frameMbsOnly = reader.Bit(); + if (frameMbsOnly == 0) reader.Bit(); + reader.Bit(); + std::uint32_t cropLeft = 0, cropRight = 0, cropTop = 0, cropBottom = 0; + if (reader.Bit() != 0) { + cropLeft = reader.Ue(); + cropRight = reader.Ue(); + cropTop = reader.Ue(); + cropBottom = reader.Ue(); + } + if (reader.failed) return false; + const std::uint32_t cropX = chromaFormat == 0 || chromaFormat == 3 ? 1 : 2; + const std::uint32_t cropY = (chromaFormat == 1 ? 2 : 1) * (2 - frameMbsOnly); + decoder.width = widthMbs * 16 - (cropLeft + cropRight) * cropX; + decoder.height = (2 - frameMbsOnly) * heightMapUnits * 16 - (cropTop + cropBottom) * cropY; + decoder.profile = profile; + decoder.level = level; + return true; +} + +void ScanAccessUnit(const std::uint8_t* data, std::size_t size, Decoder& decoder) { + for (std::size_t index = 0; index + 4 < size; ++index) { + if (data[index] == 0 && data[index + 1] == 0 && data[index + 2] == 1 && (data[index + 3] & 0x1fu) == 7) { + ParseSps(data + index + 3, size - index - 3, decoder); + return; + } + } + for (std::size_t index = 0; index + 5 <= size;) { + const std::size_t length = (static_cast(data[index]) << 24u) | (static_cast(data[index + 1]) << 16u) | (static_cast(data[index + 2]) << 8u) | data[index + 3]; + if (length == 0 || length > size - index - 4) return; + if ((data[index + 4] & 0x1fu) == 7) { + ParseSps(data + index + 4, length, decoder); + return; + } + index += 4 + length; + } +} + +void FillBlack(void* buffer, std::uint64_t bytes, std::uint32_t width, std::uint32_t height) { + const auto luma = ChromaOffset(width, height); + const auto lumaBytes = luma < bytes ? luma : bytes; + std::memset(buffer, 0x10, lumaBytes); + if (bytes > lumaBytes) std::memset(static_cast(buffer) + lumaBytes, 0x80, bytes - lumaBytes); +} + +void Emit(Decoder& decoder, FrameBuffer* frame, OutputInfo* output, const Picture* picture) { + output->isValid = picture != nullptr; + output->isErrorFrame = false; + output->pictureCount = picture != nullptr ? 1 : 0; + output->codecType = decoder.codec; + if (!picture) return; + const auto width = decoder.width != 0 ? decoder.width : 1920u; + const auto height = decoder.height != 0 ? decoder.height : 1080u; + const auto pitch = AlignUp(width, PitchAlignment); + void* target = frame ? frame->frameBuffer : nullptr; + const auto bytes = frame ? frame->frameBufferSize : 0; + if (target && bytes != 0) FillBlack(target, bytes, width, height); + if (frame) frame->isAccepted = true; + output->frameWidth = width; + output->framePitch = pitch; + output->frameHeight = height; + output->frameBuffer = target; + output->frameBufferSize = bytes; + if (Fits(output, offsetof(OutputInfo, framePitchInBytes) + 4)) { + output->frameFormat = 0; + output->framePitchInBytes = pitch; + } + decoder.pictures[target] = *picture; +} + +std::shared_ptr FindDecoder(std::uint64_t handle) { + std::lock_guard guard(lock); + const auto found = decoders.find(handle); + return found != decoders.end() ? found->second : nullptr; +} + +#if APS5_HAVE_FFMPEG + +bool OpenCodec(Decoder& decoder) { + const AVCodec* codec = avcodec_find_decoder(AV_CODEC_ID_H264); + if (codec == nullptr) return false; + decoder.context = avcodec_alloc_context3(codec); + if (decoder.context == nullptr) return false; + decoder.context->thread_count = 0; + decoder.context->thread_type = FF_THREAD_SLICE; + if (avcodec_open2(decoder.context, codec, nullptr) < 0) { + avcodec_free_context(&decoder.context); + return false; + } + return true; +} + +const std::vector* ToAnnexB(Decoder& decoder, const std::uint8_t* data, std::size_t size) { + if (size >= 4 && data[0] == 0 && data[1] == 0 && (data[2] == 1 || (data[2] == 0 && data[3] == 1))) { + decoder.annexB.assign(data, data + size); + return &decoder.annexB; + } + decoder.annexB.clear(); + for (std::size_t index = 0; index + 4 <= size;) { + const std::size_t length = (static_cast(data[index]) << 24u) | (static_cast(data[index + 1]) << 16u) | (static_cast(data[index + 2]) << 8u) | data[index + 3]; + if (length == 0 || length > size - index - 4) return nullptr; + static constexpr std::uint8_t startCode[4] = {0, 0, 0, 1}; + decoder.annexB.insert(decoder.annexB.end(), startCode, startCode + 4); + decoder.annexB.insert(decoder.annexB.end(), data + index + 4, data + index + 4 + length); + index += 4 + length; + } + return decoder.annexB.empty() ? nullptr : &decoder.annexB; +} + +void Receive(Decoder& decoder) { + for (;;) { + FramePointer frame(av_frame_alloc()); + if (!frame || avcodec_receive_frame(decoder.context, frame.get()) < 0) return; + decoder.ready.push_back(std::move(frame)); + } +} + +bool Send(Decoder& decoder, const AVPacket* packet) { + const int result = avcodec_send_packet(decoder.context, packet); + Receive(decoder); + return result >= 0 || result == AVERROR(EAGAIN) || result == AVERROR_EOF; +} + +bool WriteNv12(Decoder& decoder, const AVFrame& frame, std::uint8_t* target, std::uint64_t bytes) { + const auto width = static_cast(frame.width); + const auto height = static_cast(frame.height); + const auto pitch = AlignUp(width, PitchAlignment); + const auto luma = ChromaOffset(width, height); + if (luma + static_cast(pitch) * (height / 2) > bytes) return false; + std::uint8_t* planes[2] = {target, target + luma}; + const int strides[2] = {static_cast(pitch), static_cast(pitch)}; + const auto format = static_cast(frame.format); + if (format == AV_PIX_FMT_YUV420P || format == AV_PIX_FMT_YUVJ420P) { + for (std::uint32_t row = 0; row < height; ++row) std::memcpy(planes[0] + static_cast(row) * pitch, frame.data[0] + static_cast(row) * frame.linesize[0], width); + for (std::uint32_t row = 0; row < height / 2; ++row) { + const auto* u = frame.data[1] + static_cast(row) * frame.linesize[1]; + const auto* v = frame.data[2] + static_cast(row) * frame.linesize[2]; + auto* uv = planes[1] + static_cast(row) * pitch; + for (std::uint32_t column = 0; column < width / 2; ++column) { + uv[column * 2] = u[column]; + uv[column * 2 + 1] = v[column]; + } + } + return true; + } + decoder.scaler = sws_getCachedContext(decoder.scaler, frame.width, frame.height, format, frame.width, frame.height, AV_PIX_FMT_NV12, SWS_BILINEAR, nullptr, nullptr, nullptr); + if (decoder.scaler == nullptr) return false; + return sws_scale(decoder.scaler, frame.data, frame.linesize, 0, frame.height, planes, strides) == frame.height; +} + +void EmitDecoded(Decoder& decoder, FrameBuffer* frame, OutputInfo* output) { + output->isValid = false; + output->isErrorFrame = false; + output->pictureCount = 0; + output->codecType = decoder.codec; + if (frame) frame->isAccepted = false; + if (decoder.ready.empty() || !frame || !frame->frameBuffer) return; + const auto picture = std::move(decoder.ready.front()); + decoder.ready.pop_front(); + Picture timestamps{}; + const auto key = picture->pts != AV_NOPTS_VALUE ? picture->pts : picture->best_effort_timestamp; + const auto found = decoder.inputs.find(key); + if (found != decoder.inputs.end()) { + timestamps = found->second; + decoder.inputs.erase(found); + } + decoder.inputs.erase(decoder.inputs.begin(), decoder.inputs.lower_bound(key - 64)); + timestamps.idr = (picture->flags & AV_FRAME_FLAG_KEY) != 0; + decoder.width = static_cast(picture->width); + decoder.height = static_cast(picture->height); + if (decoder.context->profile > 0) decoder.profile = static_cast(decoder.context->profile) & 0xffu; + if (decoder.context->level > 0) decoder.level = static_cast(decoder.context->level); + const bool written = WriteNv12(decoder, *picture, static_cast(frame->frameBuffer), frame->frameBufferSize); + const auto pitch = AlignUp(decoder.width, PitchAlignment); + frame->isAccepted = true; + output->isValid = true; + output->isErrorFrame = !written; + output->pictureCount = 1; + output->frameWidth = decoder.width; + output->framePitch = pitch; + output->frameHeight = decoder.height; + output->frameBuffer = frame->frameBuffer; + output->frameBufferSize = frame->frameBufferSize; + if (Fits(output, offsetof(OutputInfo, framePitchInBytes) + 4)) { + output->frameFormat = 0; + output->framePitchInBytes = pitch; + } + decoder.pictures[frame->frameBuffer] = timestamps; +} + +#endif + +} + +extern "C" { + +int APS5_VABI sceVideodec2QueryComputeMemoryInfo_nid_postfix(ComputeMemoryInfo* info) { + if (!info) return SCE_VIDEODEC2_ERROR_ARGUMENT_POINTER; + if (Trace()) std::fprintf(stderr, "[videodec2] QueryComputeMemoryInfo size=%llu\n", static_cast(info->thisSize)); + info->cpuGpuMemorySize = WorkMemoryBytes; + return 0; +} + +int APS5_VABI sceVideodec2AllocateComputeQueue_nid_postfix(const ComputeConfigInfo* config, const ComputeMemoryInfo* memory, std::uint64_t* queue) { + if (!config || !memory || !queue) return SCE_VIDEODEC2_ERROR_ARGUMENT_POINTER; + if (Trace()) std::fprintf(stderr, "[videodec2] AllocateComputeQueue config=%llu memory=%llu\n", static_cast(config->thisSize), static_cast(memory->thisSize)); + std::lock_guard guard(lock); + *queue = nextQueue++; + return 0; +} + +int APS5_VABI sceVideodec2ReleaseComputeQueue_nid_postfix(std::uint64_t queue) { + (void)queue; + return 0; +} + +int APS5_VABI sceVideodec2QueryDecoderMemoryInfo_nid_postfix(const DecoderConfigInfo* config, DecoderMemoryInfo* memory) { + if (!config || !memory) return SCE_VIDEODEC2_ERROR_ARGUMENT_POINTER; + if (Trace()) std::fprintf(stderr, "[videodec2] QueryDecoderMemoryInfo config=%llu memory=%llu codec=%u profile=%u %dx%d dpb=%d\n", static_cast(config->thisSize), static_cast(memory->thisSize), config->codecType, config->profile, config->maxFrameWidth, config->maxFrameHeight, config->maxDpbFrameCount); + memory->cpuMemorySize = WorkMemoryBytes; + memory->gpuMemorySize = WorkMemoryBytes; + memory->cpuGpuMemorySize = WorkMemoryBytes; + const auto width = config->maxFrameWidth > 0 ? static_cast(config->maxFrameWidth) : 1920u; + const auto height = config->maxFrameHeight > 0 ? static_cast(config->maxFrameHeight) : 1080u; + memory->maxFrameBufferSize = LumaBytes(width, height) * 3 / 2; + memory->frameBufferAlignment = PitchAlignment; + return 0; +} + +int APS5_VABI sceVideodec2CreateDecoder_nid_postfix(const DecoderConfigInfo* config, const DecoderMemoryInfo* memory, std::uint64_t* handle) { + if (!config || !memory || !handle) return SCE_VIDEODEC2_ERROR_ARGUMENT_POINTER; + auto decoder = std::make_shared(); + decoder->codec = config->codecType; +#if APS5_HAVE_FFMPEG + const bool decoding = OpenCodec(*decoder); +#else + const bool decoding = false; +#endif + std::lock_guard guard(lock); + *handle = nextDecoder++; + decoders.emplace(*handle, decoder); + std::fprintf(stderr, "[videodec2] decoder %llu: codec=%u max %dx%d (%s)\n", static_cast(*handle), config->codecType, config->maxFrameWidth, config->maxFrameHeight, decoding ? "H.264 through FFmpeg" : "black frames, no H.264 decoder"); + return 0; +} + +int APS5_VABI sceVideodec2DeleteDecoder_nid_postfix(std::uint64_t handle) { + std::lock_guard guard(lock); + return decoders.erase(handle) != 0 ? 0 : SCE_VIDEODEC2_ERROR_DECODER_INSTANCE; +} + +int APS5_VABI sceVideodec2Decode_nid_postfix(std::uint64_t handle, const InputData* input, FrameBuffer* frame, OutputInfo* output) { + if (!input || !output) return SCE_VIDEODEC2_ERROR_ARGUMENT_POINTER; + const auto found = FindDecoder(handle); + if (!found) return SCE_VIDEODEC2_ERROR_DECODER_INSTANCE; + auto& decoder = *found; + std::lock_guard guard(decoder.mutex); + if (input->auData && input->auSize != 0 && decoder.width == 0) ScanAccessUnit(input->auData, static_cast(input->auSize), decoder); + if (Trace() && decoder.decoded < 3) std::fprintf(stderr, "[videodec2] Decode input=%llu frame=%llu output=%llu au=%llu pts=%llu size=%ux%u fb=%p/%llu\n", static_cast(input->thisSize), static_cast(frame ? frame->thisSize : 0), static_cast(output->thisSize), static_cast(input->auSize), static_cast(input->ptsData), decoder.width, decoder.height, frame ? frame->frameBuffer : nullptr, static_cast(frame ? frame->frameBufferSize : 0)); + ++decoder.decoded; + const Picture picture{input->ptsData, input->dtsData, input->attachedData}; +#if APS5_HAVE_FFMPEG + if (decoder.context != nullptr) { + if (decoder.flushing) { + avcodec_flush_buffers(decoder.context); + decoder.flushing = false; + } + const auto* unit = input->auData && input->auSize != 0 ? ToAnnexB(decoder, input->auData, static_cast(input->auSize)) : nullptr; + if (unit != nullptr) { + AVPacket* packet = av_packet_alloc(); + if (!packet) return SCE_VIDEODEC2_ERROR_ARGUMENT_POINTER; + packet->data = const_cast(unit->data()); + packet->size = static_cast(unit->size()); + packet->pts = decoder.nextKey; + decoder.inputs.emplace(decoder.nextKey++, picture); + const bool sent = Send(decoder, packet); + av_packet_free(&packet); + if (!sent && Trace()) std::fprintf(stderr, "[videodec2] decoder %llu rejected access unit %llu\n", static_cast(handle), static_cast(decoder.decoded)); + } + EmitDecoded(decoder, frame, output); + return 0; + } +#endif + Emit(decoder, frame, output, &picture); + return 0; +} + +int APS5_VABI sceVideodec2Flush_nid_postfix(std::uint64_t handle, FrameBuffer* frame, OutputInfo* output) { + if (!output) return SCE_VIDEODEC2_ERROR_ARGUMENT_POINTER; + const auto found = FindDecoder(handle); + if (!found) return SCE_VIDEODEC2_ERROR_DECODER_INSTANCE; + auto& decoder = *found; + std::lock_guard guard(decoder.mutex); +#if APS5_HAVE_FFMPEG + if (decoder.context != nullptr) { + if (!decoder.flushing) { + decoder.flushing = true; + Send(decoder, nullptr); + } + EmitDecoded(decoder, frame, output); + return 0; + } +#endif + if (frame) frame->isAccepted = false; + Emit(decoder, frame, output, nullptr); + return 0; +} + +int APS5_VABI sceVideodec2Reset_nid_postfix(std::uint64_t handle) { + const auto found = FindDecoder(handle); + if (!found) return SCE_VIDEODEC2_ERROR_DECODER_INSTANCE; + auto& decoder = *found; + std::lock_guard guard(decoder.mutex); + decoder.pictures.clear(); +#if APS5_HAVE_FFMPEG + if (decoder.context != nullptr) avcodec_flush_buffers(decoder.context); + decoder.ready.clear(); + decoder.inputs.clear(); + decoder.flushing = false; +#endif + return 0; +} + +int APS5_VABI sceVideodec2GetPictureInfo_nid_postfix(const OutputInfo* output, AvcPictureInfo* first, void* second) { + (void)second; + if (!output || !first) return SCE_VIDEODEC2_ERROR_ARGUMENT_POINTER; + std::vector> all; + { + std::lock_guard guard(lock); + for (const auto& [handle, decoder] : decoders) all.push_back(decoder); + } + for (const auto& decoder : all) { + std::lock_guard guard(decoder->mutex); + const auto found = decoder->pictures.find(output->frameBuffer); + if (found == decoder->pictures.end()) continue; + const auto& picture = found->second; + first->isValid = true; + first->ptsData = picture.pts; + first->dtsData = picture.dts; + first->attachedData = picture.attached; + if (Fits(first, offsetof(AvcPictureInfo, picHeightInLumaSamples) + 4)) { +#if APS5_HAVE_FFMPEG + first->idrPictureFlag = decoder->context != nullptr ? (picture.idr ? 1 : 0) : 1; +#else + first->idrPictureFlag = 1; +#endif + first->profileIdc = static_cast(decoder->profile); + first->levelIdc = static_cast(decoder->level); + first->picWidthInLumaSamples = output->frameWidth; + first->picHeightInLumaSamples = output->frameHeight; + } + return 0; + } + first->isValid = false; + return 0; +} + +} diff --git a/core/libs/tests/GuestVideodec2.cpp b/core/libs/tests/GuestVideodec2.cpp new file mode 100644 index 000000000..41d995813 --- /dev/null +++ b/core/libs/tests/GuestVideodec2.cpp @@ -0,0 +1,299 @@ +#include +#include +#include +#include +#include +#include +#include +#include "prx/libc/include/General.hpp" + +struct DecoderConfigInfo { + std::uint64_t thisSize; + std::uint32_t resourceType; + std::uint32_t codecType; + std::uint32_t profile; + std::uint32_t maxLevel; + std::int32_t maxFrameWidth; + std::int32_t maxFrameHeight; + std::int32_t maxDpbFrameCount; + std::uint32_t decodePipelineDepth; +}; + +struct DecoderMemoryInfo { + std::uint64_t thisSize; + std::uint64_t cpuMemorySize; + void* cpuMemory; + std::uint64_t gpuMemorySize; + void* gpuMemory; + std::uint64_t cpuGpuMemorySize; + void* cpuGpuMemory; + std::uint64_t maxFrameBufferSize; + std::uint32_t frameBufferAlignment; +}; + +struct InputData { + std::uint64_t thisSize; + const std::uint8_t* auData; + std::uint64_t auSize; + std::uint64_t ptsData; + std::uint64_t dtsData; + std::uint64_t attachedData; +}; + +struct FrameBuffer { + std::uint64_t thisSize; + void* frameBuffer; + std::uint64_t frameBufferSize; + bool isAccepted; +}; + +struct OutputInfo { + std::uint64_t thisSize; + bool isValid; + bool isErrorFrame; + std::uint8_t pictureCount; + std::uint32_t codecType; + std::uint32_t frameWidth; + std::uint32_t framePitch; + std::uint32_t frameHeight; + void* frameBuffer; + std::uint64_t frameBufferSize; + std::uint32_t frameFormat; + std::uint32_t framePitchInBytes; +}; + +struct AvcPictureInfo { + std::uint64_t thisSize; + bool isValid; + std::uint64_t ptsData; + std::uint64_t dtsData; + std::uint64_t attachedData; + std::uint8_t idrPictureFlag; + std::uint8_t profileIdc; + std::uint8_t levelIdc; + std::uint32_t picWidthInLumaSamples; + std::uint32_t picHeightInLumaSamples; +}; + +extern "C" { +int APS5_VABI sceVideodec2QueryDecoderMemoryInfo_nid_postfix(const DecoderConfigInfo*, DecoderMemoryInfo*); +int APS5_VABI sceVideodec2CreateDecoder_nid_postfix(const DecoderConfigInfo*, const DecoderMemoryInfo*, std::uint64_t*); +int APS5_VABI sceVideodec2DeleteDecoder_nid_postfix(std::uint64_t); +int APS5_VABI sceVideodec2Decode_nid_postfix(std::uint64_t, const InputData*, FrameBuffer*, OutputInfo*); +int APS5_VABI sceVideodec2Flush_nid_postfix(std::uint64_t, FrameBuffer*, OutputInfo*); +int APS5_VABI sceVideodec2Reset_nid_postfix(std::uint64_t); +int APS5_VABI sceVideodec2GetPictureInfo_nid_postfix(const OutputInfo*, AvcPictureInfo*, void*); +} + +namespace { + +constexpr std::uint32_t Width = 64; +constexpr std::uint32_t Height = 40; +constexpr int DecoderInstanceError = static_cast(0x811d0106u); + +constexpr std::array Stream{ + 0x00, 0x00, 0x00, 0x01, 0x09, 0x10, 0x00, 0x00, 0x00, 0x01, 0x67, 0x64, 0x00, 0x0a, 0xac, 0xd9, + 0x44, 0x7f, 0x97, 0x01, 0x10, 0x00, 0x00, 0x03, 0x00, 0x10, 0x00, 0x00, 0x03, 0x03, 0xc0, 0xf1, + 0x22, 0x59, 0x60, 0x00, 0x00, 0x00, 0x01, 0x68, 0xeb, 0xe3, 0xcb, 0x22, 0xc0, 0x00, 0x00, 0x01, + 0x06, 0x05, 0xff, 0xff, 0xa5, 0xdc, 0x45, 0xe9, 0xbd, 0xe6, 0xd9, 0x48, 0xb7, 0x96, 0x2c, 0xd8, + 0x20, 0xd9, 0x23, 0xee, 0xef, 0x78, 0x32, 0x36, 0x34, 0x20, 0x2d, 0x20, 0x63, 0x6f, 0x72, 0x65, + 0x20, 0x31, 0x36, 0x35, 0x20, 0x72, 0x33, 0x32, 0x32, 0x32, 0x20, 0x62, 0x33, 0x35, 0x36, 0x30, + 0x35, 0x61, 0x20, 0x2d, 0x20, 0x48, 0x2e, 0x32, 0x36, 0x34, 0x2f, 0x4d, 0x50, 0x45, 0x47, 0x2d, + 0x34, 0x20, 0x41, 0x56, 0x43, 0x20, 0x63, 0x6f, 0x64, 0x65, 0x63, 0x20, 0x2d, 0x20, 0x43, 0x6f, + 0x70, 0x79, 0x6c, 0x65, 0x66, 0x74, 0x20, 0x32, 0x30, 0x30, 0x33, 0x2d, 0x32, 0x30, 0x32, 0x35, + 0x20, 0x2d, 0x20, 0x68, 0x74, 0x74, 0x70, 0x3a, 0x2f, 0x2f, 0x77, 0x77, 0x77, 0x2e, 0x76, 0x69, + 0x64, 0x65, 0x6f, 0x6c, 0x61, 0x6e, 0x2e, 0x6f, 0x72, 0x67, 0x2f, 0x78, 0x32, 0x36, 0x34, 0x2e, + 0x68, 0x74, 0x6d, 0x6c, 0x20, 0x2d, 0x20, 0x6f, 0x70, 0x74, 0x69, 0x6f, 0x6e, 0x73, 0x3a, 0x20, + 0x63, 0x61, 0x62, 0x61, 0x63, 0x3d, 0x31, 0x20, 0x72, 0x65, 0x66, 0x3d, 0x33, 0x20, 0x64, 0x65, + 0x62, 0x6c, 0x6f, 0x63, 0x6b, 0x3d, 0x31, 0x3a, 0x30, 0x3a, 0x30, 0x20, 0x61, 0x6e, 0x61, 0x6c, + 0x79, 0x73, 0x65, 0x3d, 0x30, 0x78, 0x33, 0x3a, 0x30, 0x78, 0x31, 0x31, 0x33, 0x20, 0x6d, 0x65, + 0x3d, 0x68, 0x65, 0x78, 0x20, 0x73, 0x75, 0x62, 0x6d, 0x65, 0x3d, 0x37, 0x20, 0x70, 0x73, 0x79, + 0x3d, 0x31, 0x20, 0x70, 0x73, 0x79, 0x5f, 0x72, 0x64, 0x3d, 0x31, 0x2e, 0x30, 0x30, 0x3a, 0x30, + 0x2e, 0x30, 0x30, 0x20, 0x6d, 0x69, 0x78, 0x65, 0x64, 0x5f, 0x72, 0x65, 0x66, 0x3d, 0x31, 0x20, + 0x6d, 0x65, 0x5f, 0x72, 0x61, 0x6e, 0x67, 0x65, 0x3d, 0x31, 0x36, 0x20, 0x63, 0x68, 0x72, 0x6f, + 0x6d, 0x61, 0x5f, 0x6d, 0x65, 0x3d, 0x31, 0x20, 0x74, 0x72, 0x65, 0x6c, 0x6c, 0x69, 0x73, 0x3d, + 0x31, 0x20, 0x38, 0x78, 0x38, 0x64, 0x63, 0x74, 0x3d, 0x31, 0x20, 0x63, 0x71, 0x6d, 0x3d, 0x30, + 0x20, 0x64, 0x65, 0x61, 0x64, 0x7a, 0x6f, 0x6e, 0x65, 0x3d, 0x32, 0x31, 0x2c, 0x31, 0x31, 0x20, + 0x66, 0x61, 0x73, 0x74, 0x5f, 0x70, 0x73, 0x6b, 0x69, 0x70, 0x3d, 0x31, 0x20, 0x63, 0x68, 0x72, + 0x6f, 0x6d, 0x61, 0x5f, 0x71, 0x70, 0x5f, 0x6f, 0x66, 0x66, 0x73, 0x65, 0x74, 0x3d, 0x2d, 0x32, + 0x20, 0x74, 0x68, 0x72, 0x65, 0x61, 0x64, 0x73, 0x3d, 0x31, 0x20, 0x6c, 0x6f, 0x6f, 0x6b, 0x61, + 0x68, 0x65, 0x61, 0x64, 0x5f, 0x74, 0x68, 0x72, 0x65, 0x61, 0x64, 0x73, 0x3d, 0x31, 0x20, 0x73, + 0x6c, 0x69, 0x63, 0x65, 0x64, 0x5f, 0x74, 0x68, 0x72, 0x65, 0x61, 0x64, 0x73, 0x3d, 0x30, 0x20, + 0x6e, 0x72, 0x3d, 0x30, 0x20, 0x64, 0x65, 0x63, 0x69, 0x6d, 0x61, 0x74, 0x65, 0x3d, 0x31, 0x20, + 0x69, 0x6e, 0x74, 0x65, 0x72, 0x6c, 0x61, 0x63, 0x65, 0x64, 0x3d, 0x30, 0x20, 0x62, 0x6c, 0x75, + 0x72, 0x61, 0x79, 0x5f, 0x63, 0x6f, 0x6d, 0x70, 0x61, 0x74, 0x3d, 0x30, 0x20, 0x63, 0x6f, 0x6e, + 0x73, 0x74, 0x72, 0x61, 0x69, 0x6e, 0x65, 0x64, 0x5f, 0x69, 0x6e, 0x74, 0x72, 0x61, 0x3d, 0x30, + 0x20, 0x62, 0x66, 0x72, 0x61, 0x6d, 0x65, 0x73, 0x3d, 0x32, 0x20, 0x62, 0x5f, 0x70, 0x79, 0x72, + 0x61, 0x6d, 0x69, 0x64, 0x3d, 0x32, 0x20, 0x62, 0x5f, 0x61, 0x64, 0x61, 0x70, 0x74, 0x3d, 0x30, + 0x20, 0x62, 0x5f, 0x62, 0x69, 0x61, 0x73, 0x3d, 0x30, 0x20, 0x64, 0x69, 0x72, 0x65, 0x63, 0x74, + 0x3d, 0x31, 0x20, 0x77, 0x65, 0x69, 0x67, 0x68, 0x74, 0x62, 0x3d, 0x31, 0x20, 0x6f, 0x70, 0x65, + 0x6e, 0x5f, 0x67, 0x6f, 0x70, 0x3d, 0x30, 0x20, 0x77, 0x65, 0x69, 0x67, 0x68, 0x74, 0x70, 0x3d, + 0x32, 0x20, 0x6b, 0x65, 0x79, 0x69, 0x6e, 0x74, 0x3d, 0x36, 0x20, 0x6b, 0x65, 0x79, 0x69, 0x6e, + 0x74, 0x5f, 0x6d, 0x69, 0x6e, 0x3d, 0x31, 0x20, 0x73, 0x63, 0x65, 0x6e, 0x65, 0x63, 0x75, 0x74, + 0x3d, 0x30, 0x20, 0x69, 0x6e, 0x74, 0x72, 0x61, 0x5f, 0x72, 0x65, 0x66, 0x72, 0x65, 0x73, 0x68, + 0x3d, 0x30, 0x20, 0x72, 0x63, 0x5f, 0x6c, 0x6f, 0x6f, 0x6b, 0x61, 0x68, 0x65, 0x61, 0x64, 0x3d, + 0x36, 0x20, 0x72, 0x63, 0x3d, 0x63, 0x72, 0x66, 0x20, 0x6d, 0x62, 0x74, 0x72, 0x65, 0x65, 0x3d, + 0x31, 0x20, 0x63, 0x72, 0x66, 0x3d, 0x32, 0x33, 0x2e, 0x30, 0x20, 0x71, 0x63, 0x6f, 0x6d, 0x70, + 0x3d, 0x30, 0x2e, 0x36, 0x30, 0x20, 0x71, 0x70, 0x6d, 0x69, 0x6e, 0x3d, 0x30, 0x20, 0x71, 0x70, + 0x6d, 0x61, 0x78, 0x3d, 0x36, 0x39, 0x20, 0x71, 0x70, 0x73, 0x74, 0x65, 0x70, 0x3d, 0x34, 0x20, + 0x69, 0x70, 0x5f, 0x72, 0x61, 0x74, 0x69, 0x6f, 0x3d, 0x31, 0x2e, 0x34, 0x30, 0x20, 0x61, 0x71, + 0x3d, 0x31, 0x3a, 0x31, 0x2e, 0x30, 0x30, 0x00, 0x80, 0x00, 0x00, 0x01, 0x65, 0x88, 0x84, 0x00, + 0x21, 0xff, 0x5b, 0xff, 0x78, 0x50, 0x63, 0x8c, 0x32, 0x61, 0x08, 0xb9, 0xb3, 0xab, 0x26, 0xb5, + 0xe1, 0xe9, 0x5b, 0xb7, 0x7b, 0xfd, 0x6b, 0x41, 0x3a, 0x52, 0x12, 0x59, 0x95, 0x0c, 0xa4, 0x3b, + 0xc7, 0x28, 0x9a, 0x87, 0xd9, 0x38, 0xc9, 0xcb, 0x8f, 0x05, 0x47, 0xff, 0xd1, 0x1e, 0xd3, 0x68, + 0xb5, 0x05, 0x8c, 0xb4, 0xf3, 0x18, 0x74, 0x33, 0x57, 0x68, 0xf6, 0xf0, 0xc7, 0xcb, 0xbf, 0x7b, + 0x3d, 0x43, 0x0f, 0xa7, 0x42, 0x5a, 0x78, 0x5b, 0x61, 0x0e, 0xc6, 0x5c, 0xb2, 0xdf, 0xa0, 0xe0, + 0x96, 0x11, 0xdd, 0x02, 0xec, 0x17, 0x80, 0x72, 0x4f, 0x35, 0x05, 0x1e, 0x8b, 0xa8, 0xfc, 0x38, + 0x28, 0xa8, 0xc7, 0x19, 0x5a, 0xa0, 0x8b, 0x96, 0x47, 0x6c, 0xf3, 0x37, 0x65, 0x02, 0x13, 0x8a, + 0x97, 0xbc, 0x86, 0xf8, 0x31, 0xc2, 0xab, 0x7f, 0xe1, 0xa4, 0x68, 0x21, 0xc5, 0xe1, 0x56, 0xca, + 0x96, 0xd7, 0xa3, 0x7f, 0x77, 0x7b, 0xed, 0x28, 0x08, 0xd4, 0xe3, 0x98, 0xdc, 0xc1, 0x2f, 0x0f, + 0x0c, 0x37, 0x06, 0x36, 0xd4, 0x10, 0xdb, 0x7e, 0x99, 0xd4, 0xb1, 0x67, 0xda, 0xbd, 0x28, 0x58, + 0xe6, 0x0e, 0x70, 0x33, 0xe4, 0xb0, 0xb8, 0xd2, 0xb4, 0x60, 0x16, 0x41, 0x1d, 0xda, 0xc5, 0x47, + 0xad, 0xd3, 0x55, 0x30, 0xdf, 0xca, 0xab, 0xb9, 0x91, 0xca, 0xca, 0xe6, 0xfe, 0xb4, 0x9e, 0x55, + 0x18, 0xeb, 0x74, 0x83, 0x01, 0x95, 0xb3, 0x0c, 0x92, 0x4d, 0xb8, 0xfd, 0xa6, 0x28, 0x77, 0xdb, + 0xb9, 0xbc, 0xf2, 0x2c, 0xde, 0xe2, 0x1f, 0x55, 0x39, 0x80, 0x05, 0x67, 0xf1, 0x8c, 0x46, 0xf3, + 0xf8, 0x61, 0x00, 0x00, 0x00, 0x01, 0x09, 0x30, 0x00, 0x00, 0x01, 0x41, 0x9a, 0x23, 0x6c, 0x47, + 0x7f, 0xd6, 0x70, 0xed, 0x07, 0x2d, 0x6f, 0xf0, 0xd9, 0x1c, 0xc5, 0x57, 0x33, 0x9c, 0x0b, 0xe3, + 0x29, 0x4d, 0xc8, 0x18, 0xba, 0x21, 0x49, 0x77, 0xb9, 0xc5, 0x9c, 0xab, 0xcb, 0xca, 0xe9, 0xab, + 0xf7, 0xad, 0xfb, 0x45, 0xda, 0x68, 0x98, 0x7e, 0xff, 0xbd, 0x7e, 0x91, 0xb8, 0x93, 0xb5, 0x78, + 0x93, 0x98, 0x6e, 0x6e, 0xdf, 0x1f, 0x8f, 0x3c, 0x4e, 0xc9, 0x78, 0x17, 0xbf, 0xf4, 0xfb, 0x47, + 0x64, 0x2f, 0xb3, 0xf8, 0xb6, 0xdc, 0x1a, 0xe9, 0xb7, 0x7c, 0xfc, 0x6a, 0x5d, 0xb5, 0x95, 0xb6, + 0x47, 0x6b, 0xfe, 0x5d, 0xf6, 0x8e, 0x6e, 0x85, 0x65, 0x2a, 0x2d, 0x05, 0x21, 0x45, 0x13, 0x0d, + 0x0c, 0xf3, 0xea, 0x6f, 0x58, 0x28, 0x7a, 0x66, 0x54, 0xfd, 0x7e, 0x27, 0xc6, 0x6a, 0xf0, 0x00, + 0x00, 0x00, 0x01, 0x09, 0x50, 0x00, 0x00, 0x01, 0x41, 0x9e, 0x41, 0x78, 0x84, 0x3f, 0xe3, 0x5a, + 0x3c, 0x1e, 0x34, 0x44, 0x68, 0x14, 0xb9, 0xbc, 0x32, 0x4a, 0xc3, 0x1b, 0x54, 0xd4, 0x00, 0x3c, + 0x17, 0xa1, 0xbd, 0xc0, 0x86, 0xe1, 0xbf, 0x7d, 0xf4, 0x08, 0x3c, 0xa3, 0xeb, 0xe0, 0xfd, 0x44, + 0x09, 0x7d, 0x95, 0x20, 0xf4, 0x50, 0x4b, 0x4e, 0xf3, 0x78, 0xa5, 0x9f, 0x14, 0x23, 0x7f, 0xc1, + 0x4e, 0x94, 0xf1, 0x1b, 0xa1, 0x94, 0x86, 0x6d, 0x14, 0x53, 0xa8, 0xe6, 0xa4, 0xd4, 0x28, 0xcd, + 0x86, 0xb1, 0xcb, 0x9f, 0x67, 0x72, 0xc5, 0xf8, 0x99, 0x9a, 0xf3, 0xba, 0x47, 0xdf, 0x41, 0x00, + 0x00, 0x00, 0x01, 0x09, 0x50, 0x00, 0x00, 0x01, 0x01, 0x9e, 0x62, 0x6a, 0x42, 0x5f, 0xdf, 0xac, + 0xe9, 0x76, 0x6c, 0x13, 0x5c, 0xa1, 0x08, 0xbf, 0xd4, 0xd8, 0x03, 0xef, 0xd2, 0x0d, 0xc1, 0xde, + 0x35, 0x3b, 0x9e, 0x3d, 0xe1, 0xf6, 0xd8, 0xe7, 0xae, 0xdf, 0x9f, 0x20, 0x19, 0xbc, 0x50, 0xa9, + 0x69, 0x82, 0x26, 0x04, 0xaf, 0x83, 0x44, 0x79, 0x1b, 0x74, 0x18, 0x2b, 0x00, 0xb8, 0x62, 0xa3, + 0xd1, 0x84, 0x8b, 0x61, 0x87, 0x1a, 0x4f, 0x5b, 0xef, 0x16, 0xeb, 0xb3, 0x1a, 0x06, 0xfd, 0x92, + 0x87, 0x06, 0xc3, 0xec, 0xda, 0xde, 0xec, 0x3d, 0x7d, 0x8a, 0x06, 0x91, 0xc8, 0xdf, 0x59, 0xa7, + 0x58, 0xef, 0x7a, 0x3c, 0x27, 0x1d, 0x00, 0x00, 0x00, 0x01, 0x09, 0x30, 0x00, 0x00, 0x01, 0x41, + 0x9a, 0x65, 0x49, 0xa8, 0x41, 0x68, 0x99, 0x4c, 0x14, 0xf0, 0xc7, 0xde, 0x88, 0x44, 0x37, 0xa7, + 0x7f, 0x10, 0x1e, 0xf9, 0x41, 0xb5, 0x7c, 0x9b, 0xf7, 0x1d, 0x61, 0x0e, 0xe1, 0xec, 0xbc, 0x75, + 0x08, 0x53, 0x8f, 0x68, 0x84, 0x84, 0x93, 0x11, 0x08, 0xf6, 0xb2, 0xe5, 0x6f, 0x30, 0x16, 0xd0, + 0x9d, 0xf2, 0x87, 0x44, 0x40, 0x82, 0x85, 0xcf, 0x16, 0x73, 0x64, 0x1f, 0xb0, 0x22, 0x75, 0xc8, + 0xd7, 0xd2, 0x61, 0xdc, 0x1e, 0x9c, 0xa0, 0xeb, 0x88, 0x7d, 0x1a, 0x55, 0xe4, 0x66, 0x49, 0x5e, + 0xa8, 0xff, 0xc2, 0xb5, 0xb0, 0x46, 0x2a, 0xb5, 0xcd, 0xed, 0x7c, 0xf9, 0xd8, 0xe7, 0x00, 0x00, + 0x00, 0x01, 0x09, 0x50, 0x00, 0x00, 0x01, 0x01, 0x9e, 0x84, 0x6a, 0x42, 0x5f, 0xf9, 0x0f, 0xf0, + 0x52, 0xca, 0xb7, 0x04, 0x3a, 0xd3, 0x0a, 0xb3, 0xaa, 0x47, 0xf0, 0x8c, 0x9f, 0x4b, 0x6f, 0x0e, + 0x38, 0x62, 0x53, 0x04, 0x7d, 0x8f, 0x80, 0xca, 0x62, 0x93, 0xfd, 0xbb, 0x97, 0xef, 0x71, 0xf8, + 0xbc, 0x20, 0x23, 0xd1, 0x9d, 0x50, 0xee, 0xd4, 0x9a, 0x13, 0xb6, 0xfb, 0x78, 0x71, 0x43, 0x78, + 0x65, 0xd6, 0x24, 0xe4, 0xca, 0x6f, 0xb4, 0x42, 0x4d, 0x64, 0xd5, 0xfc, 0x12, 0x29, 0x20, 0x52, + 0xd8, 0x82, 0x78, 0x3d, 0x2f, +}; + +constexpr std::array PictureHashes{ + 0x5871fdc85dfa274eull, 0x26ce4afb974cffc4ull, 0xd2e739633733d5baull, + 0x54feb3d290e028fdull, 0xfa1342a4ba1819c8ull, 0x870125dd7f079a4cull, +}; + +constexpr std::array DisplayOrderUnits{0, 2, 3, 1, 5, 4}; + +void check(bool condition, const std::string& message) { + if (!condition) throw std::runtime_error(message); +} + +std::uint64_t hashNv12(const std::uint8_t* buffer, std::uint32_t pitch) { + std::uint64_t hash = 0xcbf29ce484222325ull; + const auto mix = [&](const std::uint8_t* row) { + for (std::uint32_t column = 0; column < Width; ++column) hash = (hash ^ row[column]) * 0x100000001b3ull; + }; + for (std::uint32_t row = 0; row < Height; ++row) mix(buffer + static_cast(row) * pitch); + const auto* chroma = buffer + static_cast(pitch) * Height; + for (std::uint32_t row = 0; row < Height / 2; ++row) mix(chroma + static_cast(row) * pitch); + return hash; +} + +std::vector> accessUnits(bool lengthPrefixed) { + std::vector starts; + for (std::size_t index = 0; index + 4 < Stream.size(); ++index) { + if (Stream[index] == 0 && Stream[index + 1] == 0 && Stream[index + 2] == 0 && Stream[index + 3] == 1 && (Stream[index + 4] & 0x1fu) == 9) starts.push_back(index); + } + starts.push_back(Stream.size()); + std::vector> units; + for (std::size_t unit = 0; unit + 1 < starts.size(); ++unit) { + if (!lengthPrefixed) { + units.emplace_back(Stream.begin() + static_cast(starts[unit]), Stream.begin() + static_cast(starts[unit + 1])); + continue; + } + std::vector nals; + for (std::size_t index = starts[unit]; index + 3 < starts[unit + 1]; ++index) { + if (Stream[index] == 0 && Stream[index + 1] == 0 && Stream[index + 2] == 1) { + nals.push_back(index + 3); + index += 2; + } + } + std::vector converted; + for (std::size_t nal = 0; nal < nals.size(); ++nal) { + auto end = nal + 1 < nals.size() ? nals[nal + 1] - 3 : starts[unit + 1]; + while (end > nals[nal] && Stream[end - 1] == 0) --end; + const auto length = end - nals[nal]; + for (int shift = 24; shift >= 0; shift -= 8) converted.push_back(static_cast(length >> shift)); + converted.insert(converted.end(), Stream.begin() + static_cast(nals[nal]), Stream.begin() + static_cast(end)); + } + units.push_back(std::move(converted)); + } + return units; +} + +void testDecode(bool lengthPrefixed) { + const DecoderConfigInfo config{sizeof(DecoderConfigInfo), 0, 1, 100, 0, static_cast(Width), static_cast(Height), 4, 1}; + DecoderMemoryInfo memory{sizeof(DecoderMemoryInfo)}; + check(sceVideodec2QueryDecoderMemoryInfo_nid_postfix(&config, &memory) == 0, "memory query failed"); + std::uint64_t handle = 0; + check(sceVideodec2CreateDecoder_nid_postfix(&config, &memory, &handle) == 0, "decoder creation failed"); + std::vector buffer(memory.maxFrameBufferSize); + std::size_t pictures = 0; + const auto take = [&](const OutputInfo& output, const FrameBuffer& frame) { + check(output.isValid == frame.isAccepted, "frame buffer acceptance disagrees with the output"); + if (!output.isValid) return false; + check(pictures < PictureHashes.size(), "more pictures than access units"); + check(!output.isErrorFrame && output.frameWidth == Width && output.frameHeight == Height && output.framePitch == 256 && output.frameBuffer == buffer.data(), "unexpected picture geometry"); + AvcPictureInfo info{sizeof(AvcPictureInfo)}; + check(sceVideodec2GetPictureInfo_nid_postfix(&output, &info, nullptr) == 0 && info.isValid, "picture info missing"); + const auto unit = DisplayOrderUnits[pictures]; + check(info.ptsData == 1000 + unit && info.dtsData == unit && info.attachedData == 0xa0 + unit, "picture timestamps out of display order"); + check(info.idrPictureFlag == (pictures == 0 ? 1 : 0) && info.profileIdc == 100, "picture flags mismatch"); + check(hashNv12(buffer.data(), output.framePitch) == PictureHashes[pictures], "picture " + std::to_string(pictures) + " differs from the reference"); + ++pictures; + return true; + }; + const auto units = accessUnits(lengthPrefixed); + check(units.size() == PictureHashes.size(), "unexpected access unit count"); + for (std::size_t unit = 0; unit < units.size(); ++unit) { + const InputData input{sizeof(InputData), units[unit].data(), units[unit].size(), 1000 + unit, unit, 0xa0 + unit}; + FrameBuffer frame{sizeof(FrameBuffer), buffer.data(), buffer.size(), false}; + OutputInfo output{sizeof(OutputInfo)}; + check(sceVideodec2Decode_nid_postfix(handle, &input, &frame, &output) == 0, "decode failed"); + take(output, frame); + } + for (;;) { + FrameBuffer frame{sizeof(FrameBuffer), buffer.data(), buffer.size(), false}; + OutputInfo output{sizeof(OutputInfo)}; + check(sceVideodec2Flush_nid_postfix(handle, &frame, &output) == 0, "flush failed"); + if (!take(output, frame)) break; + } + check(pictures == PictureHashes.size(), "missing pictures after flush"); + check(sceVideodec2Reset_nid_postfix(handle) == 0, "reset failed"); + check(sceVideodec2DeleteDecoder_nid_postfix(handle) == 0, "delete failed"); + check(sceVideodec2DeleteDecoder_nid_postfix(handle) == DecoderInstanceError, "deleted decoder still accepted"); +} + +} + +int main() { + try { + testDecode(false); + testDecode(true); + std::puts("Videodec2 tests passed"); + return 0; + } catch (const std::exception& error) { + std::fprintf(stderr, "%s\n", error.what()); + return 1; + } +} From 62cb92716a00992229dc2a89003d698c9761fc03 Mon Sep 17 00:00:00 2001 From: Pacuka <69674426+Pacuka@users.noreply.github.com> Date: Mon, 28 Sep 2026 21:04:08 +0200 Subject: [PATCH 2/4] build(videodec2): build FFmpeg from a pinned submodule Add FFmpeg n9.0.2 as the 3rdparty/FFmpeg submodule (shallow) and build it with ExternalProject_Add through its own configure and make, instead of using the system libraries from pkg-config. Only avcodec, avutil and swscale are built, with the H.264 decoder as the single component (--disable-everything, --disable-autodetect), as static PIC archives linked into libSceVideodec2.prx with --exclude-libs,ALL. Without nasm the x86 assembly is disabled. ANYPS5_ENABLE_FFMPEG=OFF, or a missing sh/make, keeps the black-picture fallback. Co-Authored-By: Claude Opus 5.5 --- .gitmodules | 4 ++ 3rdparty/FFmpeg | 1 + core/libs/prx/libSceVideodec2/CMakeLists.txt | 76 +++++++++++++++++--- docs/dev/TechnicalDebt.md | 1 + 4 files changed, 74 insertions(+), 8 deletions(-) create mode 160000 3rdparty/FFmpeg diff --git a/.gitmodules b/.gitmodules index 0a5f83fb7..72b53a34b 100644 --- a/.gitmodules +++ b/.gitmodules @@ -28,3 +28,7 @@ [submodule "3rdparty/stb"] path = 3rdparty/stb url = https://github.com/nothings/stb.git +[submodule "3rdparty/FFmpeg"] + path = 3rdparty/FFmpeg + url = https://github.com/FFmpeg/FFmpeg.git + shallow = true diff --git a/3rdparty/FFmpeg b/3rdparty/FFmpeg new file mode 160000 index 000000000..291f96f79 --- /dev/null +++ b/3rdparty/FFmpeg @@ -0,0 +1 @@ +Subproject commit 291f96f7929f5837dc900adef3720025516e8584 diff --git a/core/libs/prx/libSceVideodec2/CMakeLists.txt b/core/libs/prx/libSceVideodec2/CMakeLists.txt index 65d3b882c..a1c809a52 100644 --- a/core/libs/prx/libSceVideodec2/CMakeLists.txt +++ b/core/libs/prx/libSceVideodec2/CMakeLists.txt @@ -5,15 +5,75 @@ add_library(libSceVideodec2 SHARED EXCLUDE_FROM_ALL target_include_directories(libSceVideodec2 PRIVATE ${LIBS_INCLUDE_DIR}) configure_windows_unwind(libSceVideodec2) -find_package(PkgConfig QUIET) -if(PKG_CONFIG_FOUND) - pkg_check_modules(VIDEODEC2_FFMPEG QUIET IMPORTED_TARGET libavcodec libavutil libswscale) -endif() -if(VIDEODEC2_FFMPEG_FOUND) - target_link_libraries(libSceVideodec2 PRIVATE PkgConfig::VIDEODEC2_FFMPEG) +option(ANYPS5_ENABLE_FFMPEG "Build FFmpeg from 3rdparty/FFmpeg for H.264 decoding in libSceVideodec2" ON) + +set(VIDEODEC2_FFMPEG_SOURCE_DIR ${CMAKE_SOURCE_DIR}/3rdparty/FFmpeg) +find_program(VIDEODEC2_SH sh) +find_program(VIDEODEC2_MAKE NAMES make mingw32-make) + +if(ANYPS5_ENABLE_FFMPEG AND EXISTS ${VIDEODEC2_FFMPEG_SOURCE_DIR}/configure AND VIDEODEC2_SH AND VIDEODEC2_MAKE) + include(ExternalProject) + + set(VIDEODEC2_FFMPEG_PREFIX ${CMAKE_CURRENT_BINARY_DIR}/ffmpeg) + set(VIDEODEC2_FFMPEG_INCLUDE_DIR ${VIDEODEC2_FFMPEG_PREFIX}/include) + set(VIDEODEC2_FFMPEG_LIB_DIR ${VIDEODEC2_FFMPEG_PREFIX}/lib) + set(VIDEODEC2_FFMPEG_LIBS + ${VIDEODEC2_FFMPEG_LIB_DIR}/libavcodec.a + ${VIDEODEC2_FFMPEG_LIB_DIR}/libswscale.a + ${VIDEODEC2_FFMPEG_LIB_DIR}/libavutil.a + ) + + set(VIDEODEC2_FFMPEG_OPTIONS + --prefix=${VIDEODEC2_FFMPEG_PREFIX} + --enable-static + --disable-shared + --enable-pic + --disable-autodetect + --disable-everything + --disable-programs + --disable-doc + --disable-network + --disable-avdevice + --disable-avformat + --disable-avfilter + --disable-swresample + --enable-avcodec + --enable-avutil + --enable-swscale + --enable-decoder=h264 + ) + if(CMAKE_C_COMPILER) + list(APPEND VIDEODEC2_FFMPEG_OPTIONS --cc=${CMAKE_C_COMPILER}) + endif() + find_program(VIDEODEC2_NASM nasm) + if(NOT VIDEODEC2_NASM) + list(APPEND VIDEODEC2_FFMPEG_OPTIONS --disable-x86asm) + endif() + + cmake_host_system_information(RESULT VIDEODEC2_JOBS QUERY NUMBER_OF_LOGICAL_CORES) + + ExternalProject_Add(ffmpeg_h264 + SOURCE_DIR ${VIDEODEC2_FFMPEG_SOURCE_DIR} + PREFIX ${VIDEODEC2_FFMPEG_PREFIX} + BINARY_DIR ${VIDEODEC2_FFMPEG_PREFIX}/build + CONFIGURE_COMMAND ${VIDEODEC2_SH} ${VIDEODEC2_FFMPEG_SOURCE_DIR}/configure ${VIDEODEC2_FFMPEG_OPTIONS} + BUILD_COMMAND ${VIDEODEC2_MAKE} -j${VIDEODEC2_JOBS} + INSTALL_COMMAND ${VIDEODEC2_MAKE} install + BUILD_BYPRODUCTS ${VIDEODEC2_FFMPEG_LIBS} + EXCLUDE_FROM_ALL ON + ) + file(MAKE_DIRECTORY ${VIDEODEC2_FFMPEG_INCLUDE_DIR}) + + add_dependencies(libSceVideodec2 ffmpeg_h264) + target_include_directories(libSceVideodec2 SYSTEM PRIVATE ${VIDEODEC2_FFMPEG_INCLUDE_DIR}) + target_link_libraries(libSceVideodec2 PRIVATE ${VIDEODEC2_FFMPEG_LIBS}) + if(NOT WIN32) + target_link_libraries(libSceVideodec2 PRIVATE m) + endif() + target_link_options(libSceVideodec2 PRIVATE -Wl,--exclude-libs,ALL) target_compile_definitions(libSceVideodec2 PRIVATE APS5_HAVE_FFMPEG=1) set(VIDEODEC2_HAS_FFMPEG ON PARENT_SCOPE) - message(STATUS "libSceVideodec2: H.264 decoding with FFmpeg ${VIDEODEC2_FFMPEG_libavcodec_VERSION}") + message(STATUS "libSceVideodec2: H.264 decoding with FFmpeg from 3rdparty/FFmpeg") else() - message(STATUS "libSceVideodec2: FFmpeg not found, decoders return black pictures") + message(STATUS "libSceVideodec2: FFmpeg disabled or 3rdparty/FFmpeg missing, decoders return black pictures") endif() diff --git a/docs/dev/TechnicalDebt.md b/docs/dev/TechnicalDebt.md index 42cb70360..4bcc59cc6 100644 --- a/docs/dev/TechnicalDebt.md +++ b/docs/dev/TechnicalDebt.md @@ -13,6 +13,7 @@ Throughout the project, every function at every stage either **does exactly what it's supposed to or throws an exception**. Everywhere... except: - [libSceSaveDataDialog.native](../../core/libs/prx/libSceSaveDataDialog.native/Export.cpp) - [libSceCommonDialog](../../core/libs/prx/libSceCommonDialog/Export.cpp) +- [libSceVideodec2](../../core/libs/prx/libSceVideodec2/Export.cpp) returns black pictures for every codec except H.264, and for H.264 too when [FFmpeg](../../3rdparty/FFmpeg) is not built (`ANYPS5_ENABLE_FFMPEG=OFF`, or no `sh`/`make`, as with a plain MinGW setup) - The shader recompiler [skips baryctric coordinates](../../core/shader/recompiler/Recompiler.cpp) (is not even passed to SpirvTargetOptions at row 212). ### Unknown function info From 7ac24686219b0e381047b4becea18e57cb10b06a Mon Sep 17 00:00:00 2001 From: Pacuka <69674426+Pacuka@users.noreply.github.com> Date: Mon, 28 Sep 2026 21:36:26 +0200 Subject: [PATCH 3/4] build(videodec2): leave FFmpeg off by default on Windows FFmpeg's configure runs in the found sh and writes MSYS paths into its Makefile, which a native MinGW make cannot open (Windows CI: "No rule to make target '/d/a/.../3rdparty/FFmpeg/Makefile'"). Windows builds keep the black-picture fallback unless ANYPS5_ENABLE_FFMPEG=ON is set in an MSYS2 environment. Co-Authored-By: Claude Opus 5.5 --- core/libs/prx/libSceVideodec2/CMakeLists.txt | 7 ++++++- docs/dev/TechnicalDebt.md | 2 +- 2 files changed, 7 insertions(+), 2 deletions(-) diff --git a/core/libs/prx/libSceVideodec2/CMakeLists.txt b/core/libs/prx/libSceVideodec2/CMakeLists.txt index a1c809a52..002dceaf9 100644 --- a/core/libs/prx/libSceVideodec2/CMakeLists.txt +++ b/core/libs/prx/libSceVideodec2/CMakeLists.txt @@ -5,7 +5,12 @@ add_library(libSceVideodec2 SHARED EXCLUDE_FROM_ALL target_include_directories(libSceVideodec2 PRIVATE ${LIBS_INCLUDE_DIR}) configure_windows_unwind(libSceVideodec2) -option(ANYPS5_ENABLE_FFMPEG "Build FFmpeg from 3rdparty/FFmpeg for H.264 decoding in libSceVideodec2" ON) +if(WIN32) + set(VIDEODEC2_FFMPEG_DEFAULT OFF) +else() + set(VIDEODEC2_FFMPEG_DEFAULT ON) +endif() +option(ANYPS5_ENABLE_FFMPEG "Build FFmpeg from 3rdparty/FFmpeg for H.264 decoding in libSceVideodec2" ${VIDEODEC2_FFMPEG_DEFAULT}) set(VIDEODEC2_FFMPEG_SOURCE_DIR ${CMAKE_SOURCE_DIR}/3rdparty/FFmpeg) find_program(VIDEODEC2_SH sh) diff --git a/docs/dev/TechnicalDebt.md b/docs/dev/TechnicalDebt.md index 4bcc59cc6..5a6f77ffd 100644 --- a/docs/dev/TechnicalDebt.md +++ b/docs/dev/TechnicalDebt.md @@ -13,7 +13,7 @@ Throughout the project, every function at every stage either **does exactly what it's supposed to or throws an exception**. Everywhere... except: - [libSceSaveDataDialog.native](../../core/libs/prx/libSceSaveDataDialog.native/Export.cpp) - [libSceCommonDialog](../../core/libs/prx/libSceCommonDialog/Export.cpp) -- [libSceVideodec2](../../core/libs/prx/libSceVideodec2/Export.cpp) returns black pictures for every codec except H.264, and for H.264 too when [FFmpeg](../../3rdparty/FFmpeg) is not built (`ANYPS5_ENABLE_FFMPEG=OFF`, or no `sh`/`make`, as with a plain MinGW setup) +- [libSceVideodec2](../../core/libs/prx/libSceVideodec2/Export.cpp) returns black pictures for every codec except H.264, and for H.264 too when [FFmpeg](../../3rdparty/FFmpeg) is not built (`ANYPS5_ENABLE_FFMPEG=OFF`, the default on Windows, where FFmpeg's configure needs an MSYS2 shell and make; or no `sh`/`make`) - The shader recompiler [skips baryctric coordinates](../../core/shader/recompiler/Recompiler.cpp) (is not even passed to SpirvTargetOptions at row 212). ### Unknown function info From 1e1f0562c658f979c8c81536de37bb1822bc52a1 Mon Sep 17 00:00:00 2001 From: boykopovar Date: Wed, 30 Sep 2026 17:41:49 +0300 Subject: [PATCH 4/4] refactor(videodec2): use shared ffmpeg-core submodule + remove black fallbacks --- .gitmodules | 4 - 3rdparty/FFmpeg | 1 - core/libs/CMakeLists.txt | 18 +- core/libs/prx/libSceVideodec2/CMakeLists.txt | 78 +---- core/libs/prx/libSceVideodec2/Export.cpp | 328 ++++--------------- core/libs/tests/GuestVideodec2.cpp | 48 ++- docs/dev/TechnicalDebt.md | 1 - 7 files changed, 123 insertions(+), 355 deletions(-) delete mode 160000 3rdparty/FFmpeg diff --git a/.gitmodules b/.gitmodules index 72b53a34b..0a5f83fb7 100644 --- a/.gitmodules +++ b/.gitmodules @@ -28,7 +28,3 @@ [submodule "3rdparty/stb"] path = 3rdparty/stb url = https://github.com/nothings/stb.git -[submodule "3rdparty/FFmpeg"] - path = 3rdparty/FFmpeg - url = https://github.com/FFmpeg/FFmpeg.git - shallow = true diff --git a/3rdparty/FFmpeg b/3rdparty/FFmpeg deleted file mode 160000 index 291f96f79..000000000 --- a/3rdparty/FFmpeg +++ /dev/null @@ -1 +0,0 @@ -Subproject commit 291f96f7929f5837dc900adef3720025516e8584 diff --git a/core/libs/CMakeLists.txt b/core/libs/CMakeLists.txt index 7c0440810..1ffd4c7e9 100644 --- a/core/libs/CMakeLists.txt +++ b/core/libs/CMakeLists.txt @@ -449,16 +449,14 @@ if(BUILD_TESTING) set_tests_properties(fiber PROPERTIES ENVIRONMENT_MODIFICATION "PATH=path_list_prepend:$") endif() - if(VIDEODEC2_HAS_FFMPEG) - add_executable(guest_videodec2_tests tests/GuestVideodec2.cpp) - target_include_directories(guest_videodec2_tests PRIVATE ${CMAKE_CURRENT_SOURCE_DIR}) - target_link_libraries(guest_videodec2_tests PRIVATE libSceVideodec2 libc) - configure_windows_unwind(guest_videodec2_tests) - add_test(NAME guest_videodec2 COMMAND guest_videodec2_tests) - if(WIN32) - set_tests_properties(guest_videodec2 PROPERTIES ENVIRONMENT_MODIFICATION - "PATH=path_list_prepend:$") - endif() + add_executable(guest_videodec2_tests tests/GuestVideodec2.cpp) + target_include_directories(guest_videodec2_tests PRIVATE ${CMAKE_CURRENT_SOURCE_DIR}) + target_link_libraries(guest_videodec2_tests PRIVATE libSceVideodec2 libc) + configure_windows_unwind(guest_videodec2_tests) + add_test(NAME guest_videodec2 COMMAND guest_videodec2_tests) + if(WIN32) + set_tests_properties(guest_videodec2 PROPERTIES ENVIRONMENT_MODIFICATION + "PATH=path_list_prepend:$") endif() add_executable(mspace_tests tests/Mspace.cpp) target_include_directories(mspace_tests PRIVATE ${CMAKE_CURRENT_SOURCE_DIR}) diff --git a/core/libs/prx/libSceVideodec2/CMakeLists.txt b/core/libs/prx/libSceVideodec2/CMakeLists.txt index 002dceaf9..b8dbc0f7d 100644 --- a/core/libs/prx/libSceVideodec2/CMakeLists.txt +++ b/core/libs/prx/libSceVideodec2/CMakeLists.txt @@ -5,80 +5,4 @@ add_library(libSceVideodec2 SHARED EXCLUDE_FROM_ALL target_include_directories(libSceVideodec2 PRIVATE ${LIBS_INCLUDE_DIR}) configure_windows_unwind(libSceVideodec2) -if(WIN32) - set(VIDEODEC2_FFMPEG_DEFAULT OFF) -else() - set(VIDEODEC2_FFMPEG_DEFAULT ON) -endif() -option(ANYPS5_ENABLE_FFMPEG "Build FFmpeg from 3rdparty/FFmpeg for H.264 decoding in libSceVideodec2" ${VIDEODEC2_FFMPEG_DEFAULT}) - -set(VIDEODEC2_FFMPEG_SOURCE_DIR ${CMAKE_SOURCE_DIR}/3rdparty/FFmpeg) -find_program(VIDEODEC2_SH sh) -find_program(VIDEODEC2_MAKE NAMES make mingw32-make) - -if(ANYPS5_ENABLE_FFMPEG AND EXISTS ${VIDEODEC2_FFMPEG_SOURCE_DIR}/configure AND VIDEODEC2_SH AND VIDEODEC2_MAKE) - include(ExternalProject) - - set(VIDEODEC2_FFMPEG_PREFIX ${CMAKE_CURRENT_BINARY_DIR}/ffmpeg) - set(VIDEODEC2_FFMPEG_INCLUDE_DIR ${VIDEODEC2_FFMPEG_PREFIX}/include) - set(VIDEODEC2_FFMPEG_LIB_DIR ${VIDEODEC2_FFMPEG_PREFIX}/lib) - set(VIDEODEC2_FFMPEG_LIBS - ${VIDEODEC2_FFMPEG_LIB_DIR}/libavcodec.a - ${VIDEODEC2_FFMPEG_LIB_DIR}/libswscale.a - ${VIDEODEC2_FFMPEG_LIB_DIR}/libavutil.a - ) - - set(VIDEODEC2_FFMPEG_OPTIONS - --prefix=${VIDEODEC2_FFMPEG_PREFIX} - --enable-static - --disable-shared - --enable-pic - --disable-autodetect - --disable-everything - --disable-programs - --disable-doc - --disable-network - --disable-avdevice - --disable-avformat - --disable-avfilter - --disable-swresample - --enable-avcodec - --enable-avutil - --enable-swscale - --enable-decoder=h264 - ) - if(CMAKE_C_COMPILER) - list(APPEND VIDEODEC2_FFMPEG_OPTIONS --cc=${CMAKE_C_COMPILER}) - endif() - find_program(VIDEODEC2_NASM nasm) - if(NOT VIDEODEC2_NASM) - list(APPEND VIDEODEC2_FFMPEG_OPTIONS --disable-x86asm) - endif() - - cmake_host_system_information(RESULT VIDEODEC2_JOBS QUERY NUMBER_OF_LOGICAL_CORES) - - ExternalProject_Add(ffmpeg_h264 - SOURCE_DIR ${VIDEODEC2_FFMPEG_SOURCE_DIR} - PREFIX ${VIDEODEC2_FFMPEG_PREFIX} - BINARY_DIR ${VIDEODEC2_FFMPEG_PREFIX}/build - CONFIGURE_COMMAND ${VIDEODEC2_SH} ${VIDEODEC2_FFMPEG_SOURCE_DIR}/configure ${VIDEODEC2_FFMPEG_OPTIONS} - BUILD_COMMAND ${VIDEODEC2_MAKE} -j${VIDEODEC2_JOBS} - INSTALL_COMMAND ${VIDEODEC2_MAKE} install - BUILD_BYPRODUCTS ${VIDEODEC2_FFMPEG_LIBS} - EXCLUDE_FROM_ALL ON - ) - file(MAKE_DIRECTORY ${VIDEODEC2_FFMPEG_INCLUDE_DIR}) - - add_dependencies(libSceVideodec2 ffmpeg_h264) - target_include_directories(libSceVideodec2 SYSTEM PRIVATE ${VIDEODEC2_FFMPEG_INCLUDE_DIR}) - target_link_libraries(libSceVideodec2 PRIVATE ${VIDEODEC2_FFMPEG_LIBS}) - if(NOT WIN32) - target_link_libraries(libSceVideodec2 PRIVATE m) - endif() - target_link_options(libSceVideodec2 PRIVATE -Wl,--exclude-libs,ALL) - target_compile_definitions(libSceVideodec2 PRIVATE APS5_HAVE_FFMPEG=1) - set(VIDEODEC2_HAS_FFMPEG ON PARENT_SCOPE) - message(STATUS "libSceVideodec2: H.264 decoding with FFmpeg from 3rdparty/FFmpeg") -else() - message(STATUS "libSceVideodec2: FFmpeg disabled or 3rdparty/FFmpeg missing, decoders return black pictures") -endif() +target_link_libraries(libSceVideodec2 PRIVATE ffmpeg) diff --git a/core/libs/prx/libSceVideodec2/Export.cpp b/core/libs/prx/libSceVideodec2/Export.cpp index 10e6d6571..055a5d509 100644 --- a/core/libs/prx/libSceVideodec2/Export.cpp +++ b/core/libs/prx/libSceVideodec2/Export.cpp @@ -8,25 +8,19 @@ #include #include #include -#include "SceTypes.hpp" +#include +#include +#include #include "prx/libc/include/General.hpp" -#if APS5_HAVE_FFMPEG extern "C" { #include #include -#include #include } -#endif - -// Tech debt: without FFmpeg (APS5_HAVE_FFMPEG unset) decoders return black NV12 pictures that -// carry the access unit timestamps, so players still advance through a movie. namespace { -constexpr int SCE_VIDEODEC2_ERROR_ARGUMENT_POINTER = static_cast(0x811d0103u); -constexpr int SCE_VIDEODEC2_ERROR_DECODER_INSTANCE = static_cast(0x811d0106u); constexpr std::uint64_t WorkMemoryBytes = 1u << 20u; constexpr std::uint32_t PitchAlignment = 256; constexpr std::uint32_t HeightAlignment = 32; @@ -119,12 +113,10 @@ struct Picture { bool idr = false; }; -#if APS5_HAVE_FFMPEG struct FrameDeleter { void operator()(AVFrame* frame) const { av_frame_free(&frame); } }; using FramePointer = std::unique_ptr; -#endif struct Decoder { std::uint32_t codec = 0; @@ -135,7 +127,6 @@ struct Decoder { std::map pictures; std::uint64_t decoded = 0; std::mutex mutex; -#if APS5_HAVE_FFMPEG AVCodecContext* context = nullptr; SwsContext* scaler = nullptr; std::map inputs; @@ -148,7 +139,6 @@ struct Decoder { sws_freeContext(scaler); avcodec_free_context(&context); } -#endif }; std::mutex lock; @@ -173,187 +163,29 @@ std::uint64_t LumaBytes(std::uint32_t width, std::uint32_t height) { return static_cast(AlignUp(width, PitchAlignment)) * AlignUp(height, HeightAlignment); } -template -bool Fits(const T* object, std::size_t end) { +template +bool Fits(const TObject* object, std::size_t end) { return object->thisSize >= end; } -class BitReader { -public: - BitReader(const std::uint8_t* data, std::size_t size) : data(data), size(size) {} - - std::uint32_t Bit() { - if (position >= size * 8) { failed = true; return 0; } - const auto bit = (data[position / 8] >> (7 - position % 8)) & 1u; - ++position; - return bit; - } - - std::uint32_t Bits(unsigned count) { - std::uint32_t value = 0; - for (unsigned index = 0; index < count; ++index) value = (value << 1u) | Bit(); - return value; - } - - std::uint32_t Ue() { - unsigned zeros = 0; - while (Bit() == 0 && !failed && zeros < 32) ++zeros; - if (zeros >= 32) { failed = true; return 0; } - return ((1u << zeros) - 1u) + Bits(zeros); - } - - std::int32_t Se() { - const auto value = Ue(); - return (value & 1u) != 0 ? static_cast((value + 1) / 2) : -static_cast(value / 2); - } - - bool failed = false; - -private: - const std::uint8_t* data; - std::size_t size; - std::size_t position = 0; -}; - -void SkipScalingList(BitReader& reader, int count) { - int last = 8; - int next = 8; - for (int index = 0; index < count; ++index) { - if (next != 0) next = (last + reader.Se() + 256) % 256; - last = next == 0 ? last : next; - } -} - -bool ParseSps(const std::uint8_t* nal, std::size_t size, Decoder& decoder) { - std::uint8_t rbsp[256]; - std::size_t length = 0; - for (std::size_t index = 1; index < size && length < sizeof(rbsp); ++index) { - if (index >= 3 && nal[index] == 3 && nal[index - 1] == 0 && nal[index - 2] == 0) continue; - rbsp[length++] = nal[index]; - } - BitReader reader(rbsp, length); - const auto profile = reader.Bits(8); - reader.Bits(8); - const auto level = reader.Bits(8); - reader.Ue(); - std::uint32_t chromaFormat = 1; - if (profile == 100 || profile == 110 || profile == 122 || profile == 244 || profile == 44 || profile == 83 || profile == 86 || profile == 118 || profile == 128) { - chromaFormat = reader.Ue(); - if (chromaFormat == 3) reader.Bit(); - reader.Ue(); - reader.Ue(); - reader.Bit(); - if (reader.Bit() != 0) { - for (int index = 0; index < (chromaFormat != 3 ? 8 : 12); ++index) { - if (reader.Bit() != 0) SkipScalingList(reader, index < 6 ? 16 : 64); - } - } - } - reader.Ue(); - const auto pocType = reader.Ue(); - if (pocType == 0) { - reader.Ue(); - } else if (pocType == 1) { - reader.Bit(); - reader.Se(); - reader.Se(); - const auto cycle = reader.Ue(); - for (std::uint32_t index = 0; index < cycle && !reader.failed; ++index) reader.Se(); - } - reader.Ue(); - reader.Bit(); - const auto widthMbs = reader.Ue() + 1; - const auto heightMapUnits = reader.Ue() + 1; - const auto frameMbsOnly = reader.Bit(); - if (frameMbsOnly == 0) reader.Bit(); - reader.Bit(); - std::uint32_t cropLeft = 0, cropRight = 0, cropTop = 0, cropBottom = 0; - if (reader.Bit() != 0) { - cropLeft = reader.Ue(); - cropRight = reader.Ue(); - cropTop = reader.Ue(); - cropBottom = reader.Ue(); - } - if (reader.failed) return false; - const std::uint32_t cropX = chromaFormat == 0 || chromaFormat == 3 ? 1 : 2; - const std::uint32_t cropY = (chromaFormat == 1 ? 2 : 1) * (2 - frameMbsOnly); - decoder.width = widthMbs * 16 - (cropLeft + cropRight) * cropX; - decoder.height = (2 - frameMbsOnly) * heightMapUnits * 16 - (cropTop + cropBottom) * cropY; - decoder.profile = profile; - decoder.level = level; - return true; -} - -void ScanAccessUnit(const std::uint8_t* data, std::size_t size, Decoder& decoder) { - for (std::size_t index = 0; index + 4 < size; ++index) { - if (data[index] == 0 && data[index + 1] == 0 && data[index + 2] == 1 && (data[index + 3] & 0x1fu) == 7) { - ParseSps(data + index + 3, size - index - 3, decoder); - return; - } - } - for (std::size_t index = 0; index + 5 <= size;) { - const std::size_t length = (static_cast(data[index]) << 24u) | (static_cast(data[index + 1]) << 16u) | (static_cast(data[index + 2]) << 8u) | data[index + 3]; - if (length == 0 || length > size - index - 4) return; - if ((data[index + 4] & 0x1fu) == 7) { - ParseSps(data + index + 4, length, decoder); - return; - } - index += 4 + length; - } -} - -void FillBlack(void* buffer, std::uint64_t bytes, std::uint32_t width, std::uint32_t height) { - const auto luma = ChromaOffset(width, height); - const auto lumaBytes = luma < bytes ? luma : bytes; - std::memset(buffer, 0x10, lumaBytes); - if (bytes > lumaBytes) std::memset(static_cast(buffer) + lumaBytes, 0x80, bytes - lumaBytes); -} - -void Emit(Decoder& decoder, FrameBuffer* frame, OutputInfo* output, const Picture* picture) { - output->isValid = picture != nullptr; - output->isErrorFrame = false; - output->pictureCount = picture != nullptr ? 1 : 0; - output->codecType = decoder.codec; - if (!picture) return; - const auto width = decoder.width != 0 ? decoder.width : 1920u; - const auto height = decoder.height != 0 ? decoder.height : 1080u; - const auto pitch = AlignUp(width, PitchAlignment); - void* target = frame ? frame->frameBuffer : nullptr; - const auto bytes = frame ? frame->frameBufferSize : 0; - if (target && bytes != 0) FillBlack(target, bytes, width, height); - if (frame) frame->isAccepted = true; - output->frameWidth = width; - output->framePitch = pitch; - output->frameHeight = height; - output->frameBuffer = target; - output->frameBufferSize = bytes; - if (Fits(output, offsetof(OutputInfo, framePitchInBytes) + 4)) { - output->frameFormat = 0; - output->framePitchInBytes = pitch; - } - decoder.pictures[target] = *picture; -} - std::shared_ptr FindDecoder(std::uint64_t handle) { std::lock_guard guard(lock); const auto found = decoders.find(handle); return found != decoders.end() ? found->second : nullptr; } -#if APS5_HAVE_FFMPEG - -bool OpenCodec(Decoder& decoder) { +void OpenCodec(Decoder& decoder) { const AVCodec* codec = avcodec_find_decoder(AV_CODEC_ID_H264); - if (codec == nullptr) return false; + if (codec == nullptr) throw std::runtime_error("Videodec2: H.264 decoder is unavailable"); decoder.context = avcodec_alloc_context3(codec); - if (decoder.context == nullptr) return false; + if (decoder.context == nullptr) throw std::runtime_error("Videodec2: cannot allocate codec context"); + decoder.context->err_recognition = AV_EF_EXPLODE; decoder.context->thread_count = 0; decoder.context->thread_type = FF_THREAD_SLICE; if (avcodec_open2(decoder.context, codec, nullptr) < 0) { avcodec_free_context(&decoder.context); - return false; + throw std::runtime_error("Videodec2: cannot open H.264 decoder"); } - return true; } const std::vector* ToAnnexB(Decoder& decoder, const std::uint8_t* data, std::size_t size) { @@ -362,39 +194,44 @@ const std::vector* ToAnnexB(Decoder& decoder, const std::uint8_t* return &decoder.annexB; } decoder.annexB.clear(); - for (std::size_t index = 0; index + 4 <= size;) { + for (std::size_t index = 0; index < size;) { + if (size - index < 4) throw std::runtime_error("Videodec2: truncated NAL length"); const std::size_t length = (static_cast(data[index]) << 24u) | (static_cast(data[index + 1]) << 16u) | (static_cast(data[index + 2]) << 8u) | data[index + 3]; - if (length == 0 || length > size - index - 4) return nullptr; + if (length == 0 || length > size - index - 4) throw std::runtime_error("Videodec2: invalid NAL length"); static constexpr std::uint8_t startCode[4] = {0, 0, 0, 1}; decoder.annexB.insert(decoder.annexB.end(), startCode, startCode + 4); decoder.annexB.insert(decoder.annexB.end(), data + index + 4, data + index + 4 + length); index += 4 + length; } - return decoder.annexB.empty() ? nullptr : &decoder.annexB; + return &decoder.annexB; } void Receive(Decoder& decoder) { for (;;) { FramePointer frame(av_frame_alloc()); - if (!frame || avcodec_receive_frame(decoder.context, frame.get()) < 0) return; + if (!frame) throw std::runtime_error("Videodec2: cannot allocate frame"); + const int result = avcodec_receive_frame(decoder.context, frame.get()); + if (result == AVERROR(EAGAIN) || result == AVERROR_EOF) return; + if (result < 0 || frame->decode_error_flags != 0) throw std::runtime_error("Videodec2: frame decoding failed"); decoder.ready.push_back(std::move(frame)); } } -bool Send(Decoder& decoder, const AVPacket* packet) { +void Send(Decoder& decoder, const AVPacket* packet) { const int result = avcodec_send_packet(decoder.context, packet); + if (result < 0) throw std::runtime_error("Videodec2: packet submission failed"); Receive(decoder); - return result >= 0 || result == AVERROR(EAGAIN) || result == AVERROR_EOF; } bool WriteNv12(Decoder& decoder, const AVFrame& frame, std::uint8_t* target, std::uint64_t bytes) { + if (frame.width <= 0 || frame.height <= 0 || frame.width % 2 != 0 || frame.height % 2 != 0) throw std::runtime_error("Videodec2: unsupported frame dimensions"); const auto width = static_cast(frame.width); const auto height = static_cast(frame.height); const auto pitch = AlignUp(width, PitchAlignment); const auto luma = ChromaOffset(width, height); if (luma + static_cast(pitch) * (height / 2) > bytes) return false; - std::uint8_t* planes[2] = {target, target + luma}; - const int strides[2] = {static_cast(pitch), static_cast(pitch)}; + std::uint8_t* planes[4] = {target, target + luma, nullptr, nullptr}; + const int strides[4] = {static_cast(pitch), static_cast(pitch), 0, 0}; const auto format = static_cast(frame.format); if (format == AV_PIX_FMT_YUV420P || format == AV_PIX_FMT_YUVJ420P) { for (std::uint32_t row = 0; row < height; ++row) std::memcpy(planes[0] + static_cast(row) * pitch, frame.data[0] + static_cast(row) * frame.linesize[0], width); @@ -420,27 +257,25 @@ void EmitDecoded(Decoder& decoder, FrameBuffer* frame, OutputInfo* output) { output->pictureCount = 0; output->codecType = decoder.codec; if (frame) frame->isAccepted = false; - if (decoder.ready.empty() || !frame || !frame->frameBuffer) return; + if (decoder.ready.empty()) return; + if (!frame || !frame->frameBuffer) throw std::runtime_error("Videodec2: missing output buffer"); const auto picture = std::move(decoder.ready.front()); decoder.ready.pop_front(); - Picture timestamps{}; - const auto key = picture->pts != AV_NOPTS_VALUE ? picture->pts : picture->best_effort_timestamp; + const auto key = picture->pts; const auto found = decoder.inputs.find(key); - if (found != decoder.inputs.end()) { - timestamps = found->second; - decoder.inputs.erase(found); - } - decoder.inputs.erase(decoder.inputs.begin(), decoder.inputs.lower_bound(key - 64)); + if (found == decoder.inputs.end()) throw std::runtime_error("Videodec2: missing picture timestamps"); + auto timestamps = found->second; + decoder.inputs.erase(found); timestamps.idr = (picture->flags & AV_FRAME_FLAG_KEY) != 0; decoder.width = static_cast(picture->width); decoder.height = static_cast(picture->height); if (decoder.context->profile > 0) decoder.profile = static_cast(decoder.context->profile) & 0xffu; if (decoder.context->level > 0) decoder.level = static_cast(decoder.context->level); - const bool written = WriteNv12(decoder, *picture, static_cast(frame->frameBuffer), frame->frameBufferSize); + if (!WriteNv12(decoder, *picture, static_cast(frame->frameBuffer), frame->frameBufferSize)) throw std::runtime_error("Videodec2: NV12 conversion failed"); const auto pitch = AlignUp(decoder.width, PitchAlignment); frame->isAccepted = true; output->isValid = true; - output->isErrorFrame = !written; + output->isErrorFrame = false; output->pictureCount = 1; output->frameWidth = decoder.width; output->framePitch = pitch; @@ -454,21 +289,19 @@ void EmitDecoded(Decoder& decoder, FrameBuffer* frame, OutputInfo* output) { decoder.pictures[frame->frameBuffer] = timestamps; } -#endif - } extern "C" { int APS5_VABI sceVideodec2QueryComputeMemoryInfo_nid_postfix(ComputeMemoryInfo* info) { - if (!info) return SCE_VIDEODEC2_ERROR_ARGUMENT_POINTER; + if (!info) throw std::runtime_error("Videodec2: invalid argument pointer"); if (Trace()) std::fprintf(stderr, "[videodec2] QueryComputeMemoryInfo size=%llu\n", static_cast(info->thisSize)); info->cpuGpuMemorySize = WorkMemoryBytes; return 0; } int APS5_VABI sceVideodec2AllocateComputeQueue_nid_postfix(const ComputeConfigInfo* config, const ComputeMemoryInfo* memory, std::uint64_t* queue) { - if (!config || !memory || !queue) return SCE_VIDEODEC2_ERROR_ARGUMENT_POINTER; + if (!config || !memory || !queue) throw std::runtime_error("Videodec2: invalid argument pointer"); if (Trace()) std::fprintf(stderr, "[videodec2] AllocateComputeQueue config=%llu memory=%llu\n", static_cast(config->thisSize), static_cast(memory->thisSize)); std::lock_guard guard(lock); *queue = nextQueue++; @@ -481,114 +314,93 @@ int APS5_VABI sceVideodec2ReleaseComputeQueue_nid_postfix(std::uint64_t queue) { } int APS5_VABI sceVideodec2QueryDecoderMemoryInfo_nid_postfix(const DecoderConfigInfo* config, DecoderMemoryInfo* memory) { - if (!config || !memory) return SCE_VIDEODEC2_ERROR_ARGUMENT_POINTER; + if (!config || !memory) throw std::runtime_error("Videodec2: invalid argument pointer"); if (Trace()) std::fprintf(stderr, "[videodec2] QueryDecoderMemoryInfo config=%llu memory=%llu codec=%u profile=%u %dx%d dpb=%d\n", static_cast(config->thisSize), static_cast(memory->thisSize), config->codecType, config->profile, config->maxFrameWidth, config->maxFrameHeight, config->maxDpbFrameCount); memory->cpuMemorySize = WorkMemoryBytes; memory->gpuMemorySize = WorkMemoryBytes; memory->cpuGpuMemorySize = WorkMemoryBytes; - const auto width = config->maxFrameWidth > 0 ? static_cast(config->maxFrameWidth) : 1920u; - const auto height = config->maxFrameHeight > 0 ? static_cast(config->maxFrameHeight) : 1080u; + if (config->maxFrameWidth <= 0 || config->maxFrameHeight <= 0) throw std::runtime_error("Videodec2: invalid frame dimensions"); + const auto width = static_cast(config->maxFrameWidth); + const auto height = static_cast(config->maxFrameHeight); memory->maxFrameBufferSize = LumaBytes(width, height) * 3 / 2; memory->frameBufferAlignment = PitchAlignment; return 0; } int APS5_VABI sceVideodec2CreateDecoder_nid_postfix(const DecoderConfigInfo* config, const DecoderMemoryInfo* memory, std::uint64_t* handle) { - if (!config || !memory || !handle) return SCE_VIDEODEC2_ERROR_ARGUMENT_POINTER; + if (!config || !memory || !handle) throw std::runtime_error("Videodec2: invalid argument pointer"); + if (config->codecType != 1) throw std::runtime_error("Videodec2: unsupported codec"); auto decoder = std::make_shared(); decoder->codec = config->codecType; -#if APS5_HAVE_FFMPEG - const bool decoding = OpenCodec(*decoder); -#else - const bool decoding = false; -#endif + OpenCodec(*decoder); std::lock_guard guard(lock); *handle = nextDecoder++; decoders.emplace(*handle, decoder); - std::fprintf(stderr, "[videodec2] decoder %llu: codec=%u max %dx%d (%s)\n", static_cast(*handle), config->codecType, config->maxFrameWidth, config->maxFrameHeight, decoding ? "H.264 through FFmpeg" : "black frames, no H.264 decoder"); + std::fprintf(stderr, "[videodec2] decoder %llu: codec=%u max %dx%d (%s)\n", static_cast(*handle), config->codecType, config->maxFrameWidth, config->maxFrameHeight, "H.264 through FFmpeg"); return 0; } int APS5_VABI sceVideodec2DeleteDecoder_nid_postfix(std::uint64_t handle) { std::lock_guard guard(lock); - return decoders.erase(handle) != 0 ? 0 : SCE_VIDEODEC2_ERROR_DECODER_INSTANCE; + if (decoders.erase(handle) == 0) throw std::runtime_error("Videodec2: invalid decoder handle"); + return 0; } int APS5_VABI sceVideodec2Decode_nid_postfix(std::uint64_t handle, const InputData* input, FrameBuffer* frame, OutputInfo* output) { - if (!input || !output) return SCE_VIDEODEC2_ERROR_ARGUMENT_POINTER; + if (!input || !output) throw std::runtime_error("Videodec2: invalid argument pointer"); const auto found = FindDecoder(handle); - if (!found) return SCE_VIDEODEC2_ERROR_DECODER_INSTANCE; + if (!found) throw std::runtime_error("Videodec2: invalid decoder handle"); auto& decoder = *found; std::lock_guard guard(decoder.mutex); - if (input->auData && input->auSize != 0 && decoder.width == 0) ScanAccessUnit(input->auData, static_cast(input->auSize), decoder); if (Trace() && decoder.decoded < 3) std::fprintf(stderr, "[videodec2] Decode input=%llu frame=%llu output=%llu au=%llu pts=%llu size=%ux%u fb=%p/%llu\n", static_cast(input->thisSize), static_cast(frame ? frame->thisSize : 0), static_cast(output->thisSize), static_cast(input->auSize), static_cast(input->ptsData), decoder.width, decoder.height, frame ? frame->frameBuffer : nullptr, static_cast(frame ? frame->frameBufferSize : 0)); ++decoder.decoded; const Picture picture{input->ptsData, input->dtsData, input->attachedData}; -#if APS5_HAVE_FFMPEG - if (decoder.context != nullptr) { - if (decoder.flushing) { - avcodec_flush_buffers(decoder.context); - decoder.flushing = false; - } - const auto* unit = input->auData && input->auSize != 0 ? ToAnnexB(decoder, input->auData, static_cast(input->auSize)) : nullptr; - if (unit != nullptr) { - AVPacket* packet = av_packet_alloc(); - if (!packet) return SCE_VIDEODEC2_ERROR_ARGUMENT_POINTER; - packet->data = const_cast(unit->data()); - packet->size = static_cast(unit->size()); - packet->pts = decoder.nextKey; - decoder.inputs.emplace(decoder.nextKey++, picture); - const bool sent = Send(decoder, packet); - av_packet_free(&packet); - if (!sent && Trace()) std::fprintf(stderr, "[videodec2] decoder %llu rejected access unit %llu\n", static_cast(handle), static_cast(decoder.decoded)); - } - EmitDecoded(decoder, frame, output); - return 0; - } -#endif - Emit(decoder, frame, output, &picture); + if (decoder.flushing) throw std::runtime_error("Videodec2: reset required after flushing"); + if (!input->auData || input->auSize == 0 || input->auSize > static_cast(std::numeric_limits::max())) throw std::runtime_error("Videodec2: invalid access unit"); + const auto* unit = ToAnnexB(decoder, input->auData, static_cast(input->auSize)); + AVPacket* packet = av_packet_alloc(); + if (!packet) throw std::runtime_error("Videodec2: cannot allocate packet"); + const auto freePacket = [](AVPacket* value) { av_packet_free(&value); }; + const std::unique_ptr packetOwner(packet, freePacket); + if (av_new_packet(packet, static_cast(unit->size())) < 0) throw std::runtime_error("Videodec2: cannot allocate packet data"); + std::memcpy(packet->data, unit->data(), unit->size()); + packet->pts = decoder.nextKey; + decoder.inputs.emplace(decoder.nextKey++, picture); + Send(decoder, packet); + EmitDecoded(decoder, frame, output); return 0; } int APS5_VABI sceVideodec2Flush_nid_postfix(std::uint64_t handle, FrameBuffer* frame, OutputInfo* output) { - if (!output) return SCE_VIDEODEC2_ERROR_ARGUMENT_POINTER; + if (!output) throw std::runtime_error("Videodec2: invalid argument pointer"); const auto found = FindDecoder(handle); - if (!found) return SCE_VIDEODEC2_ERROR_DECODER_INSTANCE; + if (!found) throw std::runtime_error("Videodec2: invalid decoder handle"); auto& decoder = *found; std::lock_guard guard(decoder.mutex); -#if APS5_HAVE_FFMPEG - if (decoder.context != nullptr) { - if (!decoder.flushing) { - decoder.flushing = true; - Send(decoder, nullptr); - } - EmitDecoded(decoder, frame, output); - return 0; + if (!decoder.flushing) { + Send(decoder, nullptr); + decoder.flushing = true; } -#endif - if (frame) frame->isAccepted = false; - Emit(decoder, frame, output, nullptr); + EmitDecoded(decoder, frame, output); return 0; } int APS5_VABI sceVideodec2Reset_nid_postfix(std::uint64_t handle) { const auto found = FindDecoder(handle); - if (!found) return SCE_VIDEODEC2_ERROR_DECODER_INSTANCE; + if (!found) throw std::runtime_error("Videodec2: invalid decoder handle"); auto& decoder = *found; std::lock_guard guard(decoder.mutex); decoder.pictures.clear(); -#if APS5_HAVE_FFMPEG - if (decoder.context != nullptr) avcodec_flush_buffers(decoder.context); + avcodec_flush_buffers(decoder.context); decoder.ready.clear(); decoder.inputs.clear(); decoder.flushing = false; -#endif return 0; } int APS5_VABI sceVideodec2GetPictureInfo_nid_postfix(const OutputInfo* output, AvcPictureInfo* first, void* second) { (void)second; - if (!output || !first) return SCE_VIDEODEC2_ERROR_ARGUMENT_POINTER; + if (!output || !first) throw std::runtime_error("Videodec2: invalid argument pointer"); std::vector> all; { std::lock_guard guard(lock); @@ -604,11 +416,7 @@ int APS5_VABI sceVideodec2GetPictureInfo_nid_postfix(const OutputInfo* output, A first->dtsData = picture.dts; first->attachedData = picture.attached; if (Fits(first, offsetof(AvcPictureInfo, picHeightInLumaSamples) + 4)) { -#if APS5_HAVE_FFMPEG - first->idrPictureFlag = decoder->context != nullptr ? (picture.idr ? 1 : 0) : 1; -#else - first->idrPictureFlag = 1; -#endif + first->idrPictureFlag = picture.idr ? 1 : 0; first->profileIdc = static_cast(decoder->profile); first->levelIdc = static_cast(decoder->level); first->picWidthInLumaSamples = output->frameWidth; diff --git a/core/libs/tests/GuestVideodec2.cpp b/core/libs/tests/GuestVideodec2.cpp index 41d995813..5a7e8227a 100644 --- a/core/libs/tests/GuestVideodec2.cpp +++ b/core/libs/tests/GuestVideodec2.cpp @@ -89,7 +89,6 @@ namespace { constexpr std::uint32_t Width = 64; constexpr std::uint32_t Height = 40; -constexpr int DecoderInstanceError = static_cast(0x811d0106u); constexpr std::array Stream{ 0x00, 0x00, 0x00, 0x01, 0x09, 0x10, 0x00, 0x00, 0x00, 0x01, 0x67, 0x64, 0x00, 0x0a, 0xac, 0xd9, @@ -241,6 +240,50 @@ std::vector> accessUnits(bool lengthPrefixed) { return units; } +template +void checkThrows(TAction action) { + bool threw = false; + try { + action(); + } catch (const std::runtime_error&) { + threw = true; + } + check(threw, "expected a decoding exception"); +} + +void testFailures() { + DecoderConfigInfo config{sizeof(DecoderConfigInfo), 0, 2, 100, 0, static_cast(Width), static_cast(Height), 4, 1}; + DecoderMemoryInfo memory{sizeof(DecoderMemoryInfo)}; + std::uint64_t handle = 0; + checkThrows([&] { sceVideodec2CreateDecoder_nid_postfix(&config, &memory, &handle); }); + check(handle == 0, "unsupported codec created a decoder"); + config.codecType = 1; + config.maxFrameWidth = 0; + checkThrows([&] { sceVideodec2QueryDecoderMemoryInfo_nid_postfix(&config, &memory); }); + config.maxFrameWidth = Width; + check(sceVideodec2QueryDecoderMemoryInfo_nid_postfix(&config, &memory) == 0, "memory query failed"); + check(sceVideodec2CreateDecoder_nid_postfix(&config, &memory, &handle) == 0, "decoder creation failed"); + std::vector buffer(memory.maxFrameBufferSize); + FrameBuffer frame{sizeof(FrameBuffer), buffer.data(), buffer.size(), false}; + OutputInfo output{sizeof(OutputInfo)}; + const std::array malformed{0, 0, 0, 8, 0x65}; + InputData input{sizeof(InputData), malformed.data(), malformed.size(), 0, 0, 0}; + checkThrows([&] { sceVideodec2Decode_nid_postfix(handle, &input, &frame, &output); }); + input.auSize = 2; + checkThrows([&] { sceVideodec2Decode_nid_postfix(handle, &input, &frame, &output); }); + check(sceVideodec2Reset_nid_postfix(handle) == 0, "reset failed"); + frame.frameBufferSize = 1; + checkThrows([&] { + for (const auto& unit : accessUnits(false)) { + input.auData = unit.data(); + input.auSize = unit.size(); + sceVideodec2Decode_nid_postfix(handle, &input, &frame, &output); + } + sceVideodec2Flush_nid_postfix(handle, &frame, &output); + }); + check(sceVideodec2DeleteDecoder_nid_postfix(handle) == 0, "delete failed"); +} + void testDecode(bool lengthPrefixed) { const DecoderConfigInfo config{sizeof(DecoderConfigInfo), 0, 1, 100, 0, static_cast(Width), static_cast(Height), 4, 1}; DecoderMemoryInfo memory{sizeof(DecoderMemoryInfo)}; @@ -281,13 +324,14 @@ void testDecode(bool lengthPrefixed) { check(pictures == PictureHashes.size(), "missing pictures after flush"); check(sceVideodec2Reset_nid_postfix(handle) == 0, "reset failed"); check(sceVideodec2DeleteDecoder_nid_postfix(handle) == 0, "delete failed"); - check(sceVideodec2DeleteDecoder_nid_postfix(handle) == DecoderInstanceError, "deleted decoder still accepted"); + checkThrows([&] { sceVideodec2DeleteDecoder_nid_postfix(handle); }); } } int main() { try { + testFailures(); testDecode(false); testDecode(true); std::puts("Videodec2 tests passed"); diff --git a/docs/dev/TechnicalDebt.md b/docs/dev/TechnicalDebt.md index 5a6f77ffd..42cb70360 100644 --- a/docs/dev/TechnicalDebt.md +++ b/docs/dev/TechnicalDebt.md @@ -13,7 +13,6 @@ Throughout the project, every function at every stage either **does exactly what it's supposed to or throws an exception**. Everywhere... except: - [libSceSaveDataDialog.native](../../core/libs/prx/libSceSaveDataDialog.native/Export.cpp) - [libSceCommonDialog](../../core/libs/prx/libSceCommonDialog/Export.cpp) -- [libSceVideodec2](../../core/libs/prx/libSceVideodec2/Export.cpp) returns black pictures for every codec except H.264, and for H.264 too when [FFmpeg](../../3rdparty/FFmpeg) is not built (`ANYPS5_ENABLE_FFMPEG=OFF`, the default on Windows, where FFmpeg's configure needs an MSYS2 shell and make; or no `sh`/`make`) - The shader recompiler [skips baryctric coordinates](../../core/shader/recompiler/Recompiler.cpp) (is not even passed to SpirvTargetOptions at row 212). ### Unknown function info