diff --git a/.github/workflows/validate.yml b/.github/workflows/validate.yml index 3e6019fe70..924dba9314 100644 --- a/.github/workflows/validate.yml +++ b/.github/workflows/validate.yml @@ -58,7 +58,7 @@ jobs: - name: Install Dependencies (Linux) run: |- sudo apt update - sudo apt install -y ninja-build llvm-${{ env.LLVM_VERSION }}-dev libgtk-3-dev \ + sudo apt install -y ninja-build nasm llvm-${{ env.LLVM_VERSION }}-dev libgtk-3-dev \ libasound2-dev libpulse-dev libpipewire-0.3-dev libaudio-dev libjack-dev libsndio-dev \ libx11-dev libxext-dev libxrandr-dev libxcursor-dev libxfixes-dev libxi-dev libxss-dev libxtst-dev \ libwayland-dev libdecor-0-dev libxkbcommon-dev \ diff --git a/.gitmodules b/.gitmodules index d56f6999e4..b6e57cd639 100644 --- a/.gitmodules +++ b/.gitmodules @@ -49,6 +49,3 @@ [submodule "thirdparty/plume"] path = thirdparty/plume url = https://github.com/renderbag/plume -[submodule "thirdparty/ffmpeg-core"] - path = thirdparty/ffmpeg-core - url = https://github.com/sonicnext-dev/ffmpeg-core diff --git a/MarathonRecomp/CMakeLists.txt b/MarathonRecomp/CMakeLists.txt index 19dba88ab3..3fa7a23a20 100644 --- a/MarathonRecomp/CMakeLists.txt +++ b/MarathonRecomp/CMakeLists.txt @@ -138,8 +138,8 @@ set(MARATHON_RECOMP_GPU_CXX_SOURCES set(MARATHON_RECOMP_APU_CXX_SOURCES "apu/audio.cpp" - "apu/xma_decoder.cpp" "apu/embedded_player.cpp" + "apu/host_pcm.cpp" "apu/driver/sdl3_driver.cpp" ) @@ -172,6 +172,7 @@ set(MARATHON_RECOMP_PATCHES_CXX_SOURCES "patches/TitleTask_patches.cpp" "patches/ui_toggle_listener.cpp" "patches/video_patches.cpp" + "patches/xma_patches.cpp" ) set(MARATHON_RECOMP_UI_CXX_SOURCES @@ -392,6 +393,7 @@ if (MARATHON_RECOMP_FLATPAK) endif() find_package(CURL REQUIRED) +find_package(FFMPEG REQUIRED) if (MARATHON_RECOMP_METAL) target_compile_definitions(MarathonRecomp PRIVATE MARATHON_RECOMP_METAL) @@ -443,11 +445,10 @@ target_link_libraries(MarathonRecomp PRIVATE MarathonRecompLib xxHash::xxhash CURL::libcurl + ${FFMPEG_LIBRARIES} plume ) -target_link_libraries(MarathonRecomp PRIVATE ffmpeg) - target_include_directories(MarathonRecomp PRIVATE ${CMAKE_CURRENT_SOURCE_DIR} "${CMAKE_CURRENT_SOURCE_DIR}/api" diff --git a/MarathonRecomp/apu/host_pcm.cpp b/MarathonRecomp/apu/host_pcm.cpp new file mode 100644 index 0000000000..750c60408b --- /dev/null +++ b/MarathonRecomp/apu/host_pcm.cpp @@ -0,0 +1,461 @@ +#include "host_pcm.h" +#include + +extern "C" +{ +#include +#include +#include +#include +} + +// The guest engine mixes at most this many channels, so only layouts above it are reduced. +static constexpr int MAX_CHANNELS = 6; + +static void LogAvError(const char* action, int result) +{ + char message[AV_ERROR_MAX_STRING_SIZE]{}; + av_strerror(result, message, sizeof(message)); + + LOGFN_ERROR("Failed to {}: {}", action, message); +} + +static std::optional GetTagValue(const AVDictionary* pDict, std::initializer_list keys) +{ + for (auto key : keys) + { + if (auto* pEntry = av_dict_get(pDict, key, nullptr, 0)) + return static_cast(strtoul(pEntry->value, nullptr, 10)); + } + + return std::nullopt; +} + +HostPcm::~HostPcm() +{ + av_frame_free(&m_pFrame); + av_packet_free(&m_pPacket); + swr_free(&m_pSwr); + avcodec_free_context(&m_pCodec); + avformat_close_input(&m_pFormat); +} + +std::shared_ptr HostPcm::Open(const std::filesystem::path& path, std::optional layout) +{ + std::error_code ec; + + if (!std::filesystem::is_regular_file(path, ec)) + return nullptr; + + std::shared_ptr pcm(new HostPcm()); + + pcm->m_path = path; + pcm->m_layout = std::move(layout); + + if (!pcm->OpenInput(path)) + return nullptr; + + return pcm; +} + +bool HostPcm::OpenInput(const std::filesystem::path& path) +{ + auto utf8Path = path.u8string(); + auto* pPath = reinterpret_cast(utf8Path.c_str()); + + int result = avformat_open_input(&m_pFormat, pPath, nullptr, nullptr); + + if (result < 0) + { + LogAvError("open input", result); + return false; + } + + result = avformat_find_stream_info(m_pFormat, nullptr); + + if (result < 0) + { + LogAvError("find stream info", result); + return false; + } + + const AVCodec* pDecoder = nullptr; + m_streamIndex = av_find_best_stream(m_pFormat, AVMEDIA_TYPE_AUDIO, -1, -1, &pDecoder, 0); + + if (m_streamIndex < 0) + { + LogAvError("find audio stream", m_streamIndex); + return false; + } + + m_pStream = m_pFormat->streams[m_streamIndex]; + + m_pCodec = avcodec_alloc_context3(pDecoder); + avcodec_parameters_to_context(m_pCodec, m_pStream->codecpar); + m_pCodec->pkt_timebase = m_pStream->time_base; + + result = avcodec_open2(m_pCodec, pDecoder, nullptr); + + if (result < 0) + { + LogAvError("open decoder", result); + return false; + } + + const int sourceChannels = m_pCodec->ch_layout.nb_channels; + + m_channels = std::min(sourceChannels, MAX_CHANNELS); + m_sampleRate = m_pCodec->sample_rate; + + AVChannelLayout outLayout{}; + + if (sourceChannels <= MAX_CHANNELS) + av_channel_layout_copy(&outLayout, &m_pCodec->ch_layout); + else + av_channel_layout_default(&outLayout, MAX_CHANNELS); + + result = swr_alloc_set_opts2(&m_pSwr, &outLayout, AV_SAMPLE_FMT_S16, m_sampleRate, + &m_pCodec->ch_layout, m_pCodec->sample_fmt, m_pCodec->sample_rate, 0, nullptr); + + av_channel_layout_uninit(&outLayout); + + if (result >= 0) + result = swr_init(m_pSwr); + + if (result < 0) + { + LogAvError("create resampler", result); + return false; + } + + // The length is only an estimate, Read corrects it. + const AVRational frameBase{ 1, static_cast(m_sampleRate) }; + int64_t frames = 0; + + if (m_layout) + { + // XMA files do not have a duration that ffmpeg can read. + // The last seek table entry is the exact length. + frames = m_layout->m_blockEnds.empty() ? 0 : m_layout->m_blockEnds.back(); + } + else if (m_pStream->duration != AV_NOPTS_VALUE) + { + frames = av_rescale_q(m_pStream->duration, m_pStream->time_base, frameBase); + } + else if (m_pFormat->duration != AV_NOPTS_VALUE) + { + frames = av_rescale_q(m_pFormat->duration, AV_TIME_BASE_Q, frameBase); + } + + if (frames <= 0) + { + LOGFN_ERROR("Cannot determine the length of {}", pPath); + return false; + } + + m_frameCount = static_cast(frames); + m_pPacket = av_packet_alloc(); + m_pFrame = av_frame_alloc(); + + ReadLoopPoints(); + + return true; +} + +// Loop points are read from LOOPSTART/LOOPEND or LOOPSTART/LOOPLENGTH tags, in samples. +// Without usable tags the whole track loops. +void HostPcm::ReadLoopPoints() +{ + const AVDictionary* dictionaries[] = { m_pStream->metadata, m_pFormat->metadata }; + + std::optional begin, end, length; + + for (auto* pDict : dictionaries) + { + if (!pDict) + continue; + + if (!begin) + begin = GetTagValue(pDict, { "LOOPSTART", "LOOP_START" }); + + if (!end) + end = GetTagValue(pDict, { "LOOPEND", "LOOP_END" }); + + if (!length) + length = GetTagValue(pDict, { "LOOPLENGTH", "LOOP_LENGTH" }); + } + + m_loopBegin = begin.value_or(0); + m_loopEnd = end ? *end : length ? m_loopBegin + *length : m_frameCount; + m_loopEnd = std::min(m_loopEnd, m_frameCount); + + if (m_loopEnd <= m_loopBegin) + { + m_loopBegin = 0; + m_loopEnd = m_frameCount; + } +} + +uint32_t HostPcm::GetFrameCount() +{ + std::lock_guard lock(m_mutex); + + return m_frameCount > m_startOffset ? m_frameCount - m_startOffset : 0; +} + +void HostPcm::SetStartOffset(uint32_t frames) +{ + std::lock_guard lock(m_mutex); + + m_startOffset = frames; +} + +void HostPcm::SetLengthChangedCallback(std::function callback) +{ + std::lock_guard lock(m_mutex); + + m_lengthChanged = std::move(callback); +} + +void HostPcm::SetFrameCount(uint32_t frames) +{ + if (frames == m_frameCount) + return; + + m_frameCount = frames; + + if (m_lengthChanged) + m_lengthChanged(frames > m_startOffset ? frames - m_startOffset : 0); +} + +void HostPcm::ResetDecoder(int64_t target) +{ + m_pending.clear(); + m_pendingOffset = 0; + m_pendingStart = target; + m_nextIndex = 0; + m_targetIndex = target; + m_needSync = false; + m_draining = false; + m_eof = false; + + avcodec_flush_buffers(m_pCodec); + + swr_close(m_pSwr); + swr_init(m_pSwr); +} + +bool HostPcm::Seek(int64_t target) +{ + ResetDecoder(target); + + if (m_layout) + { + const auto& ends = m_layout->m_blockEnds; + const size_t block = std::min( + std::upper_bound(ends.begin(), ends.end(), target) - ends.begin(), ends.size() - 1); + + const int64_t offset = m_layout->m_dataOffset + static_cast(block) * m_layout->m_blockSize; + + if (avformat_seek_file(m_pFormat, -1, offset, offset, offset, AVSEEK_FLAG_BYTE) < 0) + return RestartFromStart(target); + + m_nextIndex = block != 0 ? ends[block - 1] : 0; + + return true; + } + + const AVRational frameBase{ 1, static_cast(m_sampleRate) }; + const int64_t start = m_pStream->start_time != AV_NOPTS_VALUE ? m_pStream->start_time : 0; + const int64_t preroll = std::min(target, m_sampleRate / 2); + const int64_t timestamp = start + av_rescale_q(target - preroll, frameBase, m_pStream->time_base); + + if (avformat_seek_file(m_pFormat, m_streamIndex, INT64_MIN, timestamp, timestamp, 0) < 0) + return RestartFromStart(target); + + m_needSync = true; + + return true; +} + +bool HostPcm::RestartFromStart(int64_t target) +{ + ResetDecoder(target); + + if (!Reopen()) + { + LOGN_ERROR("Failed to rewind audio stream"); + + m_eof = true; + return false; + } + + return true; +} + +// Some containers cannot seek at all, so open the file again instead. +bool HostPcm::Reopen() +{ + avformat_close_input(&m_pFormat); + + auto utf8Path = m_path.u8string(); + + if (avformat_open_input(&m_pFormat, reinterpret_cast(utf8Path.c_str()), nullptr, nullptr) < 0) + { + m_pStream = nullptr; + return false; + } + + if (m_streamIndex >= static_cast(m_pFormat->nb_streams)) + return false; + + m_pStream = m_pFormat->streams[m_streamIndex]; + + return true; +} + +void HostPcm::AppendFrame() +{ + if (m_needSync) + { + const AVRational frameBase{ 1, static_cast(m_sampleRate) }; + const int64_t start = m_pStream->start_time != AV_NOPTS_VALUE ? m_pStream->start_time : 0; + const int64_t timestamp = m_pFrame->best_effort_timestamp; + + int64_t index = INT64_MIN; + + if (timestamp != AV_NOPTS_VALUE) + index = av_rescale_q(timestamp - start, m_pStream->time_base, frameBase); + + // Without a timestamp, or after landing past the target, the position cannot be trusted. + if (index == INT64_MIN || index > m_targetIndex) + { + RestartFromStart(m_targetIndex); + return; + } + + m_nextIndex = index; + m_needSync = false; + } + + const int count = m_pFrame->nb_samples; + const int capacity = swr_get_out_samples(m_pSwr, count); + + if (capacity <= 0) + return; + + m_scratch.resize(static_cast(capacity) * m_channels); + + auto* pOutput = reinterpret_cast(m_scratch.data()); + const int frames = swr_convert(m_pSwr, &pOutput, capacity, + m_pFrame->extended_data, count); + + if (frames <= 0) + return; + + const int64_t skip = std::clamp(m_targetIndex - m_nextIndex, 0, frames); + + m_pending.insert(m_pending.end(), + m_scratch.begin() + skip * m_channels, + m_scratch.begin() + frames * m_channels); + + m_nextIndex += frames; +} + +// Decodes one more frame into m_pending. Returns false once the stream is exhausted. +bool HostPcm::DecodeMore() +{ + while (!m_eof) + { + int result = avcodec_receive_frame(m_pCodec, m_pFrame); + + if (result >= 0) + { + AppendFrame(); + av_frame_unref(m_pFrame); + + return true; + } + + if (result == AVERROR(EAGAIN) && !m_draining) + { + if (av_read_frame(m_pFormat, m_pPacket) < 0) + { + // A null packet drains the decoder. + m_draining = true; + avcodec_send_packet(m_pCodec, nullptr); + } + else + { + if (m_pPacket->stream_index == m_streamIndex) + avcodec_send_packet(m_pCodec, m_pPacket); + + av_packet_unref(m_pPacket); + } + + continue; + } + + if (result != AVERROR_EOF && result != AVERROR(EAGAIN)) + LogAvError("decode audio", result); + + m_eof = true; + } + + return false; +} + +uint32_t HostPcm::Read(uint32_t startFrame, uint32_t frameCount, int16_t* dst) +{ + std::lock_guard lock(m_mutex); + + startFrame += m_startOffset; + + if (startFrame != m_pendingStart && !Seek(startFrame)) + return 0; + + uint32_t written = 0; + + while (written < frameCount) + { + const size_t available = (m_pending.size() - m_pendingOffset) / m_channels; + + if (available == 0) + { + if (!DecodeMore()) + break; + + continue; + } + + const size_t count = std::min(frameCount - written, available); + + memcpy(dst + static_cast(written) * m_channels, + m_pending.data() + m_pendingOffset, count * m_channels * sizeof(int16_t)); + + m_pendingOffset += count * m_channels; + m_pendingStart += count; + written += static_cast(count); + } + + // Drop what was handed out, the leftover is less than one decoded frame. + m_pending.erase(m_pending.begin(), m_pending.begin() + static_cast(m_pendingOffset)); + m_pendingOffset = 0; + + const uint32_t end = startFrame + written; + + if (written < frameCount) + { + // Ran into the end of the stream before the estimate said it would. + SetFrameCount(end); + } + else if (end >= m_frameCount) + { + // Served the last block of the estimate, look ahead: there may be more audio. + while (m_pending.empty() && DecodeMore()) {} + + SetFrameCount(end + static_cast(m_pending.size() / m_channels)); + } + + return written; +} diff --git a/MarathonRecomp/apu/host_pcm.h b/MarathonRecomp/apu/host_pcm.h new file mode 100644 index 0000000000..85162fccef --- /dev/null +++ b/MarathonRecomp/apu/host_pcm.h @@ -0,0 +1,79 @@ +#pragma once + +struct AVFormatContext; +struct AVCodecContext; +struct SwrContext; +struct AVPacket; +struct AVFrame; +struct AVStream; + +struct HostPcmXmaLayout +{ + uint32_t m_dataOffset{}; + uint32_t m_blockSize{}; + std::vector m_blockEnds; +}; + +// Streams an audio file as interleaved 16-bit PCM. +class HostPcm +{ +public: + static std::shared_ptr Open(const std::filesystem::path& path, + std::optional layout = std::nullopt); + + ~HostPcm(); + + uint32_t GetChannels() const { return m_channels; } + uint32_t GetSampleRate() const { return m_sampleRate; } + uint32_t GetLoopBegin() const { return m_loopBegin; } + uint32_t GetLoopEnd() const { return m_loopEnd; } + + uint32_t GetFrameCount(); + void SetStartOffset(uint32_t frames); + void SetLengthChangedCallback(std::function callback); + uint32_t Read(uint32_t startFrame, uint32_t frameCount, int16_t* dst); + +private: + HostPcm() = default; + + std::mutex m_mutex; + + AVFormatContext* m_pFormat{}; + AVCodecContext* m_pCodec{}; + SwrContext* m_pSwr{}; + AVPacket* m_pPacket{}; + AVFrame* m_pFrame{}; + AVStream* m_pStream{}; + int m_streamIndex{}; + + uint32_t m_channels{}; + uint32_t m_sampleRate{}; + uint32_t m_loopBegin{}; + uint32_t m_loopEnd{}; + uint32_t m_frameCount{}; + uint32_t m_startOffset{}; + std::function m_lengthChanged; + + // Decoded frames not yet handed out. m_pendingStart is the stream index of the first one. + std::vector m_pending; + std::vector m_scratch; + size_t m_pendingOffset{}; // In samples + int64_t m_pendingStart{}; + int64_t m_nextIndex{}; // Stream index of the next converted frame + int64_t m_targetIndex{}; // Converted frames before this are dropped + bool m_needSync{}; // The next decoded frame's timestamp gives the position + bool m_draining{}; // End of input reached + bool m_eof{}; // Decoder fully drained + std::filesystem::path m_path; + std::optional m_layout; + + bool Reopen(); + bool OpenInput(const std::filesystem::path& path); + void ReadLoopPoints(); + void ResetDecoder(int64_t target); + bool Seek(int64_t target); + bool RestartFromStart(int64_t target); + bool DecodeMore(); + void AppendFrame(); + void SetFrameCount(uint32_t frames); +}; diff --git a/MarathonRecomp/apu/xma_decoder.cpp b/MarathonRecomp/apu/xma_decoder.cpp deleted file mode 100644 index ef23b77030..0000000000 --- a/MarathonRecomp/apu/xma_decoder.cpp +++ /dev/null @@ -1,955 +0,0 @@ -/** -****************************************************************************** -* Xenia : Xbox 360 Emulator Research Project * -****************************************************************************** -* Copyright 2024 Xenia Canary. All rights reserved. * -* Released under the BSD license - see LICENSE in the root for more details. * -****************************************************************************** -*/ - -// Almost all decoding code is from Xenia Canary, so leave the copyright here - -#include -#include -#include -#include -#include -#include - -extern "C" { - #include -} - -// #define ENABLE_DEBUG_XMA_DECODER - -#ifdef ENABLE_DEBUG_XMA_DECODER -#define debug_printf(...) printf(__VA_ARGS__) -#else -#define debug_printf(...) -#endif - -constexpr uint32_t kBytesPerPacket = 2048; -constexpr uint32_t kBytesPerPacketHeader = 4; -constexpr uint32_t kBytesPerPacketData = kBytesPerPacket - kBytesPerPacketHeader; -constexpr uint32_t kBytesPerSample = 2; -constexpr uint32_t kSamplesPerFrame = 512; -constexpr uint32_t kBytesPerFrameChannel = kSamplesPerFrame * kBytesPerSample; - -constexpr uint32_t kOutputBytesPerBlock = 256; -constexpr uint32_t kBitsPerPacketHeader = 32; -constexpr uint32_t kBitsPerPacket = kBytesPerPacket * 8; -constexpr uint32_t kMaxFrameLength = 0x7FFF; -constexpr uint32_t kBitsPerFrameHeader = 15; -constexpr uint32_t kMaxFrameSizeinBits = 0x4000 - kBitsPerPacketHeader; - -struct XMAPLAYBACKINIT { - be sampleRate; - be outputBufferSize; - uint8_t channelCount; - uint8_t subframes; -}; - -void DecoderThreadFunc(void* playback); - -struct XmaPlayback { - uint32_t sampleRate; - uint32_t outputBufferSize; - uint32_t channelCount; - uint32_t subframes; - uint8_t* outputBuffer; - uint32_t outputBufferVirtual; - uint32_t currentDataSize; - - uint32_t partialBytesRead = 0; - uint32_t streamPosition = 0; - - // ffmpeg - AVCodecContext *codec_ctx = nullptr; - const AVCodec *codec = nullptr; - AVPacket *av_packet_ = nullptr; - AVFrame *av_frame_ = nullptr; - - // xenia - std::array inputBuffer; - std::array xmaFrame; - std::array rawFrame; - uint32_t outputBufferBlockCount = 0; - uint32_t outputBufferReadOffset = 0; - uint32_t outputBufferWriteOffset = 0; - int32_t remainingSubframeBlocksInOutputBuffer = 0; - uint8_t currentFrameRemainingSubframes = 0; - uint32_t inputBufferReadOffset = 32; - - uint32_t numSubframesToSkip = 0; - - RingBuffer outputRb; - uint32_t inputBuffer1 = 0; - uint32_t inputBuffer2 = 0; - size_t inputBuffer1Size = 0; - size_t inputBuffer2Size = 0; - uint32_t validInputBuffer = 0; - std::atomic inputBuffer1Valid = 0; - std::atomic inputBuffer2Valid = 0; - uint32_t currentBuffer = 0; - - uint32_t outputBufferValid = 1; - - uint8_t numLoops = 0; - uint8_t loopSubframeEnd = 0; - uint8_t loopSubframeSkip = 0; - uint32_t loopStartOffset = 0; - uint32_t loopEndOffset = 0; - - std::unique_ptr decoderThread; - std::mutex mutex; - std::condition_variable cv; - std::atomic isLocked { false }; - std::atomic isRunning { true }; - - XmaPlayback(uint32_t sampleRate, uint32_t outputBufferSize, - uint32_t channelCount, uint32_t subframes) - : sampleRate(sampleRate), outputBufferSize(outputBufferSize), - channelCount(channelCount), subframes(subframes), - outputRb(nullptr, 0) { - outputBufferBlockCount = - (((channelCount * outputBufferSize) << 15) & 0x7C00000) >> 22; - outputBuffer = - static_cast(g_userHeap.AllocPhysical(0x2000, 0)); - outputBufferVirtual = g_memory.MapVirtual(outputBuffer); - - codec = avcodec_find_decoder(AV_CODEC_ID_XMAFRAMES); - if (!codec) { - throw std::runtime_error("Decoder not found"); - } - - codec_ctx = avcodec_alloc_context3(codec); - if (!codec_ctx) { - throw std::runtime_error("Failed to allocate codec context"); - } - - codec_ctx->sample_rate = sampleRate; - codec_ctx->ch_layout.nb_channels = channelCount; - - av_frame_ = av_frame_alloc(); - if (!av_frame_) { - throw std::runtime_error("Coulnd't allocate frame"); - } - - if (int err = avcodec_open2(codec_ctx, codec, nullptr); err < 0) { - throw std::runtime_error("Failed to open codec"); - } - av_packet_ = av_packet_alloc(); - - decoderThread = std::make_unique("XMA Decode Thread", DecoderThreadFunc, this); - } - - ~XmaPlayback() { - { - std::lock_guard lock(mutex); - isRunning = false; - cv.notify_one(); - } - - decoderThread->Join(); - - av_packet_free(&av_packet_); - av_frame_free(&av_frame_); - avcodec_free_context(&codec_ctx); - - g_userHeap.Free(outputBuffer); - } - - const uint32_t GetInputBufferAddress(uint8_t bufferIndex) const { - return bufferIndex == 0 ? inputBuffer1 : inputBuffer2; - } - - const uint32_t GetCurrentInputBufferAddress() const { - return GetInputBufferAddress(currentBuffer); - } - - const uint32_t GetInputBufferPacketCount(uint8_t bufferIndex) const { - return bufferIndex == 0 ? inputBuffer1Size : inputBuffer2Size; - } - const uint32_t GetCurrentInputBufferPacketCount() const { - return GetInputBufferPacketCount(currentBuffer); - } - - uint8_t *GetCurrentInputBuffer() { - return (uint8_t *)g_memory.Translate(GetCurrentInputBufferAddress()); - } - - bool IsInputBufferValid(uint8_t bufferIndex) const { - return bufferIndex == 0 ? inputBuffer1Valid : inputBuffer2Valid; - } - - bool IsCurrentInputBufferValid() const { - return IsInputBufferValid(currentBuffer); - } - - bool IsAnyInputBufferValid() const { - return inputBuffer1Valid || inputBuffer2Valid; - } -}; - - -uint32_t XMAPlaybackGetFrameOffsetFromPacketHeader(uint32_t header) { - uint32_t result = 0; - - if (header != 0x7FFF) { - return ((header >> 11) & 0x7FFF) + 32; - } - - return result; -} - -int16_t GetPacketNumber(size_t size, size_t bitOffset) { - if (bitOffset < kBitsPerPacketHeader) { - return -1; - } - - if (bitOffset >= (size << 3)) { - return -1; - } - - size_t byteOffset = bitOffset >> 3; - size_t packetNumber = byteOffset / kBytesPerPacket; - - return (int16_t)packetNumber; -} - -static uint32_t GetPacketFrameOffset(const uint8_t *packet) { - uint32_t val = (uint16_t)(((packet[0] & 0x3) << 13) | (packet[1] << 5) | (packet[2] >> 3)); - return val + 32; -} - -struct kPacketInfo { - uint8_t frameCount; - uint8_t currentFrame; - uint32_t currentFrameSize; - - const bool IsLastFrameInPacket() const { - return currentFrame == frameCount - 1; - } -}; - -kPacketInfo GetPacketInfo(uint8_t *packet, uint32_t frameOffset) { - kPacketInfo packetInfo = {}; - - const uint32_t firstFrameOffset = GetPacketFrameOffset(packet); - BitStream stream(packet, kBitsPerPacket); - stream.SetOffset(firstFrameOffset); - - // Handling of split frame - if (frameOffset < firstFrameOffset) { - packetInfo.currentFrame = 0; - packetInfo.currentFrameSize = firstFrameOffset - frameOffset; - } - - while (true) { - if (stream.BitsRemaining() < kBitsPerFrameHeader) { - break; - } - - const uint64_t frameSize = stream.Peek(kBitsPerFrameHeader); - if (frameSize == kMaxFrameLength) { - break; - } - - if (stream.offset_bits() == frameOffset) { - packetInfo.currentFrame = packetInfo.frameCount; - packetInfo.currentFrameSize = (uint32_t)frameSize; - } - - packetInfo.frameCount++; - - if (frameSize > stream.BitsRemaining()) { - // Last frame. - break; - } - - stream.Advance(frameSize - 1); - - // Read the trailing bit to see if frames follow - if (stream.Read(1) == 0) { - break; - } - } - - return packetInfo; -} - -uint8_t *GetNextPacket(XmaPlayback *playback, uint32_t nextPacketIndex, uint32_t currentInputPacketCount) { - if (nextPacketIndex < currentInputPacketCount) { - uint8_t *currentInputBuffer = (uint8_t *)g_memory.Translate(playback->GetCurrentInputBufferAddress()); - return currentInputBuffer + nextPacketIndex * kBytesPerPacket; - } - - const uint8_t nextBufferIndex = playback->currentBuffer ^ 1; - - if (!playback->IsInputBufferValid(nextBufferIndex)) { - return nullptr; - } - - const uint32_t nextBufferAddress = playback->GetInputBufferAddress(nextBufferIndex); - - if (!nextBufferAddress) { - // This should never occur, but there is always a chance - debug_printf("XmaContext: Buffer is marked as valid, but doesn't have valid pointer!\n"); - return nullptr; - } - - return (uint8_t *)g_memory.Translate(nextBufferAddress); -} - -uint8_t GetPacketSkipCount(const uint8_t *packet) { return packet[3]; } - -uint32_t GetAmountOfBitsToRead(const uint32_t remainingStreamBits, const uint32_t frameSize) { - return std::min(remainingStreamBits, frameSize); -} - -template T clamp_float(T value, T minValue, T maxValue) { - float clampedToMin = std::isgreater(value, minValue) ? value : minValue; - return std::isless(clampedToMin, maxValue) ? clampedToMin : maxValue; -} - -const uint32_t GetNextPacketReadOffset(uint8_t *buffer, uint32_t nextPacketIndex, - uint32_t currentInputPacketCount) { - if (nextPacketIndex >= currentInputPacketCount) { - return kBitsPerPacketHeader; - } - - uint8_t *nextPacket = buffer + (nextPacketIndex * kBytesPerPacket); - const uint32_t packetFrameOffset = GetPacketFrameOffset(nextPacket); - - if (packetFrameOffset > kMaxFrameSizeinBits) { - const uint32_t offset = GetNextPacketReadOffset(buffer, nextPacketIndex + 1, currentInputPacketCount); - return offset; - } - - const uint32_t newInputBufferOffset = (nextPacketIndex * kBitsPerPacket) + packetFrameOffset; - - return newInputBufferOffset; -} - -void SwapInputBuffer(XmaPlayback *playback) { - // No more frames. - if (playback->currentBuffer == 0) { - playback->inputBuffer1Valid = 0; - } else { - playback->inputBuffer2Valid = 0; - } - - playback->currentBuffer ^= 1; - playback->inputBufferReadOffset = kBitsPerPacketHeader; -} - -void UpdateLoopStatus(XmaPlayback *playback) { - if (playback->numLoops == 0) { - return; - } - - const uint32_t loop_start = std::max(kBitsPerPacketHeader, playback->loopStartOffset); - const uint32_t loop_end = std::max(kBitsPerPacketHeader, playback->loopEndOffset); - - if (playback->inputBufferReadOffset != loop_end) { - return; - } - - playback->inputBufferReadOffset = loop_start; - playback->numSubframesToSkip = playback->loopSubframeSkip; - - if (playback->numLoops != 255) { - playback->numLoops--; - } -} - -void Decode(XmaPlayback *playback) { - if (!playback->IsAnyInputBufferValid()) { - return; - } - - if (playback->currentFrameRemainingSubframes > 0) { - return; - } - - uint8_t *currentInputBuffer = playback->GetCurrentInputBuffer(); - - playback->inputBuffer.fill(0); - - UpdateLoopStatus(playback); // TODO - - const uint32_t currentInputSize = playback->GetCurrentInputBufferPacketCount() * kBytesPerPacket; - uint32_t currentInputPacketCount = currentInputSize / kBytesPerPacket; - int16_t packetIndex = GetPacketNumber(currentInputSize, playback->inputBufferReadOffset); - - if (packetIndex == -1) { - return; - } - - uint8_t *packet = currentInputBuffer + (packetIndex * kBytesPerPacket); - - const uint32_t frameOffset = GetPacketFrameOffset(packet); - if (playback->inputBufferReadOffset < frameOffset) { - playback->inputBufferReadOffset = frameOffset; - } - - uint32_t relativeOffset = playback->inputBufferReadOffset % kBitsPerPacket; - const kPacketInfo packetInfo = GetPacketInfo(packet, relativeOffset); - const uint32_t packetToSkip = GetPacketSkipCount(packet) + 1; - const uint32_t nextPacketIndex = packetIndex + packetToSkip; - - BitStream stream = BitStream(currentInputBuffer, (packetIndex + 1) * kBitsPerPacket); - stream.SetOffset(playback->inputBufferReadOffset); - - const uint64_t bitsToCopy = GetAmountOfBitsToRead((uint32_t)stream.BitsRemaining(), - packetInfo.currentFrameSize); - - if (bitsToCopy == 0) { - SwapInputBuffer(playback); - return; - } - - if (packetInfo.IsLastFrameInPacket()) { - // Frame is a split frame - if (stream.BitsRemaining() < packetInfo.currentFrameSize) { - const uint8_t *nextPacket = GetNextPacket(playback, nextPacketIndex, currentInputPacketCount); - - if (!nextPacket) { - // Error path - // Decoder probably should return error here - // Not sure what error code should be returned - // data->error_status = 4; - __builtin_debugtrap(); - return; - } - - // Copy next packet to buffer - std::memcpy(playback->inputBuffer.data() + kBytesPerPacketData, - nextPacket + kBytesPerPacketHeader, kBytesPerPacketData); - } - } - - std::memcpy(playback->inputBuffer.data(), packet + kBytesPerPacketHeader, kBytesPerPacketData); - - stream = BitStream(playback->inputBuffer.data(), (kBitsPerPacket - kBitsPerPacketHeader) * 2); - stream.SetOffset(relativeOffset - kBitsPerPacketHeader); - - playback->xmaFrame.fill(0); - - const uint32_t paddingStart = static_cast(stream.Copy(playback->xmaFrame.data() + 1, - packetInfo.currentFrameSize)); - - playback->rawFrame.fill(0); - playback->av_packet_->data = playback->xmaFrame.data(); - playback->av_packet_->size = static_cast(1 + ((paddingStart + packetInfo.currentFrameSize) / 8) + - (((paddingStart + packetInfo.currentFrameSize) % 8) ? 1 : 0)); - - auto paddingEnd = playback->av_packet_->size * 8 - (8 + paddingStart + packetInfo.currentFrameSize); - playback->xmaFrame[0] = ((paddingStart & 7) << 5) | ((paddingEnd & 7) << 2); - - auto ret = avcodec_send_packet(playback->codec_ctx, playback->av_packet_); - if (ret < 0) { - debug_printf("Error sending packet for decoding: %s\n", av_err2str(ret)); - } - - ret = avcodec_receive_frame(playback->codec_ctx, playback->av_frame_); - if (ret < 0) { - debug_printf("Error receiving frame from decoder: %s\n", av_err2str(ret)); - } - - constexpr float scale = (1 << 15) - 1; - auto out = reinterpret_cast(playback->rawFrame.data()); - auto samples = reinterpret_cast(&playback->av_frame_->data); - - uint32_t o = 0; - if (playback->av_frame_->nb_samples != 0) { - for (uint32_t i = 0; i < kSamplesPerFrame; i++) { - for (uint32_t j = 0; j < playback->av_frame_->ch_layout.nb_channels; j++) { - // Select the appropriate array based on the current channel. - auto in = reinterpret_cast(samples[j]); - - // Raw samples sometimes aren't within [-1, 1] - float scaledSample = clamp_float(in[i], -1.0f, 1.0f) * scale; - - // Convert the sample and output it in big endian. - auto sample = static_cast(scaledSample); - out[o++] = ByteSwap(sample); - } - } - } - - playback->currentFrameRemainingSubframes = (4 - std::min(playback->numSubframesToSkip, 4)) - * playback->channelCount; - playback->numSubframesToSkip = 0; - - if (!packetInfo.IsLastFrameInPacket()) { - const uint32_t nextFrameOffset = (playback->inputBufferReadOffset + bitsToCopy) % kBitsPerPacket; - - playback->inputBufferReadOffset = (packetIndex * kBitsPerPacket) + nextFrameOffset; - return; - } - - uint32_t nextInputOffset = GetNextPacketReadOffset(currentInputBuffer, nextPacketIndex, - currentInputPacketCount); - - if (nextInputOffset == kBitsPerPacketHeader) { - SwapInputBuffer(playback); - - // We're at start of next buffer - // Any frames in this packet decoder should go to the first frame in the packet. - // If it doesn't have any frames, then it should immediately go to the next packet. - if (playback->IsAnyInputBufferValid()) { - nextInputOffset = GetPacketFrameOffset((uint8_t *)g_memory.Translate( - playback->GetCurrentInputBufferAddress())); - - if (nextInputOffset > kMaxFrameSizeinBits) { - SwapInputBuffer(playback); - return; - } - } - } - - playback->inputBufferReadOffset = nextInputOffset; -} - -void Consume(XmaPlayback *playback) { - if (!playback->currentFrameRemainingSubframes) { - return; - } - - const int8_t subframesToWrite = std::min((int8_t)playback->currentFrameRemainingSubframes, - (int8_t)playback->subframes); - - const int8_t rawFrameReadOffset = ((kBytesPerFrameChannel / kOutputBytesPerBlock) * playback->channelCount) - - playback->currentFrameRemainingSubframes; - - playback->outputRb.Write(playback->rawFrame.data() + - (kOutputBytesPerBlock * rawFrameReadOffset), - subframesToWrite * kOutputBytesPerBlock); - playback->remainingSubframeBlocksInOutputBuffer -= subframesToWrite; - playback->currentFrameRemainingSubframes -= subframesToWrite; -} - -void DecoderThreadFunc(void* data) { - auto* playback = static_cast(data); - std::unique_lock lock(playback->mutex); - - while (playback->isRunning) { - playback->cv.wait(lock, [&] { - return !playback->isRunning || (playback->outputBufferValid == 1 && - playback->IsAnyInputBufferValid()); - }); - - if (!playback->isRunning) - break; - - const int32_t minimumSubframeDecodeCount = (playback->subframes * playback->channelCount) - 1; - - size_t outputCapacity = playback->outputBufferBlockCount * kOutputBytesPerBlock; - - const uint32_t outputReadOffset = playback->outputBufferReadOffset * kOutputBytesPerBlock; - const uint32_t outputWriteOffset = playback->outputBufferWriteOffset * kOutputBytesPerBlock; - - playback->outputRb = RingBuffer(playback->outputBuffer, outputCapacity); - playback->outputRb.set_read_offset(outputReadOffset); - playback->outputRb.set_write_offset(outputWriteOffset); - playback->remainingSubframeBlocksInOutputBuffer = (int32_t)playback->outputRb.write_count() - / kOutputBytesPerBlock; - - if (minimumSubframeDecodeCount > playback->remainingSubframeBlocksInOutputBuffer) { - playback->outputBufferValid = 0; - continue; - } - - Decode(playback); - Consume(playback); - - playback->outputBufferWriteOffset = playback->outputRb.write_offset() / kOutputBytesPerBlock; - - if (playback->outputRb.write_offset() != outputWriteOffset && playback->outputRb.empty()) { - playback->outputBufferValid = 0; - } - - lock.unlock(); - std::this_thread::yield(); - lock.lock(); - } -} - -uint32_t XMAPlaybackCreate(uint32_t streams, XMAPLAYBACKINIT *init, uint32_t flags, be *outPlayback) { - const auto xmaPlayback = g_userHeap.AllocPhysical( - init->sampleRate.get(), init->outputBufferSize.get(), init->channelCount, - init->subframes); - *outPlayback = g_memory.MapVirtual(xmaPlayback); - - return 0; -} - -uint32_t XMAPlaybackRequestModifyLock(XmaPlayback *playback) { - std::lock_guard lock(playback->mutex); - playback->isLocked = true; - - return 0; -} - -uint32_t XMAPlaybackWaitUntilModifyLockObtained(XmaPlayback *playback) { - std::unique_lock lock(playback->mutex); - playback->cv.wait(lock, [&playback] { return playback->isLocked.load(); }); - - return 0; -} - -uint32_t XMAPlaybackQueryReadyForMoreData(XmaPlayback *playback, uint32_t stream) { - return playback->inputBuffer1Valid == 0 || playback->inputBuffer2Valid == 0; -} - -uint32_t XMAPlaybackIsIdle(XmaPlayback *playback, uint32_t stream) { - return playback->inputBuffer1Valid == 0 && playback->inputBuffer2Valid == 0; -} - -uint32_t XMAPlaybackQueryContextsAllocated(XmaPlayback *playback) { - if (!playback) { - return 0; - } - - return 1; -} - -uint32_t XMAPlaybackResumePlayback(XmaPlayback *playback) { - std::lock_guard lock(playback->mutex); - playback->isLocked = false; - playback->cv.notify_all(); - - return 0; -} - -uint32_t XMAPlaybackQueryInputDataPending(XmaPlayback *playback, uint32_t stream, uint32_t data) { - if (playback->inputBuffer1Valid && playback->inputBuffer1 == data) { - return 1; - } - - if (playback->inputBuffer2Valid && playback->inputBuffer2 == data) { - return 1; - } - - return 0; -} - -uint32_t XMAPlaybackGetErrorBits(XmaPlayback *playback, uint32_t stream) { - return 0; -} - -uint32_t XMAPlaybackSubmitData(XmaPlayback *playback, uint32_t stream, uint32_t data, uint32_t dataSize) { - if (!playback->isLocked) { - return 1; - } - - std::lock_guard lock(playback->mutex); - uint32_t packetCount = dataSize >> 11; - - uint32_t validBuffer = playback->inputBuffer1Valid | (playback->inputBuffer2Valid << 1); - - if (playback->inputBuffer1Valid == 1) { - if (playback->inputBuffer2Valid == 1) { - return 0x80070005; - } - playback->inputBuffer2 = data; - playback->inputBuffer2Size = packetCount & 0xFFF; - - playback->inputBuffer2Valid = 1; - } else { - playback->inputBuffer1 = data; - playback->inputBuffer1Size = packetCount & 0xFFF; - - playback->inputBuffer1Valid = 1; - } - - if (!validBuffer) { - playback->currentBuffer = 0; - - uint8_t *currentInputBuffer = (uint8_t *)g_memory.Translate(data); - uint32_t frameOffset = XMAPlaybackGetFrameOffsetFromPacketHeader(*currentInputBuffer); - - if (frameOffset) { - playback->inputBufferReadOffset = frameOffset & 0x3FFFFFF; - } - } - - playback->cv.notify_all(); - return 0; -} - -uint32_t XMAPlaybackQueryAvailableData(XmaPlayback *playback, uint32_t stream) { - if (!playback->isLocked) { - return 0; - } - - std::lock_guard lock(playback->mutex); - - uint32_t partialBytesRead = playback->partialBytesRead; - uint32_t writeBufferOffsetRead = playback->outputBufferReadOffset & 0x1F; - uint32_t offsetWrite = playback->outputBufferWriteOffset; - uint32_t sizeWrite = playback->outputBufferBlockCount & 0x1F; - - uint32_t availableBytes = 0; - uint32_t isValidWrite = playback->outputBufferValid; - - if (partialBytesRead) { - availableBytes = 256 - partialBytesRead; - writeBufferOffsetRead++; - isValidWrite = 1; - } - - uint32_t availableBlocks = 0; - if (offsetWrite <= writeBufferOffsetRead) { - if (offsetWrite < writeBufferOffsetRead || !isValidWrite) { - availableBlocks = sizeWrite - writeBufferOffsetRead; - } - } else { - availableBlocks = offsetWrite - writeBufferOffsetRead; - } - - uint32_t totalBytes = (availableBlocks << 8) + availableBytes; - uint32_t bytesPerSample = playback->channelCount; - - return totalBytes >> bytesPerSample; -} - - -uint32_t XMAPlaybackAccessDecodedData(XmaPlayback *playback, uint32_t stream, be* data) { - if (!playback->isLocked) - return 0; - - std::lock_guard lock(playback->mutex); - - uint32_t partialBytesRead = playback->partialBytesRead; - uint32_t addr = playback->outputBufferVirtual + - ((playback->outputBufferReadOffset << 8) & 0x1F00) + - partialBytesRead; - - *data = addr; - - uint32_t writeBufferOffsetRead = playback->outputBufferReadOffset & 0x1F; - uint32_t offsetWrite = playback->outputBufferWriteOffset; - uint32_t sizeWrite = playback->outputBufferBlockCount & 0x1F; - - uint32_t availableBytes = 0; - uint32_t isValidWrite = playback->outputBufferValid; - - if (partialBytesRead) { - availableBytes = 256 - partialBytesRead; - writeBufferOffsetRead++; - isValidWrite = 1; - } - - uint32_t availableBlocks = 0; - if (offsetWrite <= writeBufferOffsetRead) { - if (offsetWrite < writeBufferOffsetRead || !isValidWrite) { - availableBlocks = sizeWrite - writeBufferOffsetRead; - } - } else { - availableBlocks = offsetWrite - writeBufferOffsetRead; - } - - uint32_t totalBytes = (availableBlocks << 8) + availableBytes; - uint32_t bytesPerSample = playback->channelCount; - - return totalBytes >> bytesPerSample; -} - -uint32_t XMAPlaybackConsumeDecodedData(XmaPlayback *playback, uint32_t stream, uint32_t maxSamples, be* data) { - if (!playback->isLocked) { - return 0; - } - - std::lock_guard lock(playback->mutex); - - uint32_t totalBytes = 0; - uint32_t partialBytesRead = playback->partialBytesRead; - uint32_t addr = playback->outputBufferVirtual + - ((playback->outputBufferReadOffset << 8) & 0x1F00) + - partialBytesRead; - - *data = addr; - uint32_t bytesPerSample = playback->channelCount; - uint32_t bytesDesired = maxSamples << bytesPerSample; - if (partialBytesRead) { - if (bytesDesired < 256 - partialBytesRead) { - totalBytes = bytesDesired; - playback->partialBytesRead += bytesDesired; - bytesDesired = 0; - } else { - totalBytes = 256 - partialBytesRead; - bytesDesired -= 256 - partialBytesRead; - playback->partialBytesRead = 0; - - uint32_t writeIndex = playback->outputBufferReadOffset + 1 & 0x1F; - - if (writeIndex >= (playback->outputBufferBlockCount & 0x1F)) { - writeIndex = 0; - } - - playback->outputBufferReadOffset = writeIndex; - playback->outputBufferValid = 1; - } - } - - uint32_t writeIndex = playback->outputBufferReadOffset; - uint32_t blocksToProcess = bytesDesired >> 8; - uint32_t availableBlocks = 0; - - uint32_t writeSize = playback->outputBufferBlockCount; - if (writeSize <= writeIndex) { - if (writeSize < writeIndex || !playback->outputBufferValid) { - availableBlocks = (playback->outputBufferBlockCount & 0x1F) - writeIndex; - } - } else { - availableBlocks = writeSize - writeIndex; - } - - if (blocksToProcess) { - if (blocksToProcess > availableBlocks) { - blocksToProcess = availableBlocks; - } - - totalBytes += blocksToProcess << 8; - availableBlocks -= blocksToProcess; - writeIndex = (writeIndex + blocksToProcess) & 0x1F; - - if (writeIndex >= (playback->outputBufferBlockCount & 0x1F)) { - writeIndex = 0; - } - - playback->outputBufferReadOffset = writeIndex; - playback->outputBufferValid = 1; - } - - uint32_t remainingBytes = bytesDesired & 0xFF; - if (remainingBytes && availableBlocks) { - totalBytes += remainingBytes; - playback->partialBytesRead = remainingBytes; - } - - playback->cv.notify_all(); - - uint32_t samplesConsumed = totalBytes >> bytesPerSample; - playback->streamPosition += samplesConsumed; - - return samplesConsumed; -} - -uint32_t XMAPlaybackQueryModifyLockObtained(XmaPlayback *playback) { - debug_printf("XMAPlaybackQueryModifyLockObtained %x\n", playback); - return playback->isLocked.load(); -} - -uint32_t XMAPlaybackDestroy(XmaPlayback *playback) { - debug_printf("XMAPlaybackDestroy %x\n", playback); - - playback->~XmaPlayback(); - g_userHeap.Free(playback); - - return 0; -} - -uint32_t XMAPlaybackFlushData(XmaPlayback *playback) { - debug_printf("XMAPlaybackFlushData %x\n", playback); - // __builtin_debugtrap(); - return 0; -} - -struct XMAPLAYBACKLOOP { - be loopStartOffset; - be loopEndOffset; - uint8_t loopSubframeEnd; - uint8_t loopSubframeSkip; - uint8_t numLoops; - uint8_t reserved; -}; - -uint32_t XmaPlaybackSetLoop(XmaPlayback *playback, uint32_t streamIndex, XMAPLAYBACKLOOP *loop) { - std::lock_guard lock(playback->mutex); - - playback->numLoops = loop->numLoops; - playback->loopSubframeEnd = loop->loopSubframeEnd; - playback->loopSubframeSkip = loop->loopSubframeSkip; - playback->loopStartOffset = loop->loopStartOffset.get() & 0x3FFFFFF; - playback->loopEndOffset = loop->loopEndOffset.get() & 0x3FFFFFF; - - return 0; -} - -uint32_t XMAPlaybackGetRemainingLoopCount(XmaPlayback *playback) { - debug_printf("XMAPlaybackGetRemainingLoopCount %x\n", playback); - __builtin_debugtrap(); - return 0; -} - -uint32_t XMAPlaybackGetStreamPosition(XmaPlayback *playback) { - return playback->streamPosition; -} - -uint32_t XMAPlaybackSetDecodePosition(XmaPlayback *playback, uint32_t streamIndex, uint32_t bitOffset, - uint32_t subframe) { - std::lock_guard lock(playback->mutex); - - playback->inputBufferReadOffset = bitOffset & 0x3FFFFFF; - playback->numSubframesToSkip = subframe & 0x7; - return 0; -} - -uint32_t XMAPlaybackRewindDecodePosition(XmaPlayback *playback, uint32_t streamIndex, uint32_t numSamples) { - std::lock_guard lock(playback->mutex); - - uint32_t shift = 7 - (1 != 0); - uint32_t adjustedSamples = numSamples >> shift; - uint32_t writeSize = playback->outputBufferBlockCount & 0x1F; - - uint32_t newOffset; - if (adjustedSamples >= writeSize) { - newOffset = playback->inputBufferReadOffset & 0x3FFFFFF; - playback->outputBufferValid = 1; - playback->outputBufferWriteOffset = newOffset >> 27; - return 0; - } - - newOffset = playback->outputBufferWriteOffset - adjustedSamples + writeSize & 0x1F; - - if (newOffset >= writeSize) { - newOffset -= writeSize; - } - - playback->outputBufferValid = 1; - playback->outputBufferWriteOffset = newOffset; - - return 1; -} - -uint32_t XMAPlaybackQueryCurrentPosition(XmaPlayback *playback) { - debug_printf("XMAPlaybackQueryCurrentPosition %x\n", playback); - __builtin_debugtrap(); - return 0; -} - -GUEST_FUNCTION_HOOK(sub_8255C090, XMAPlaybackCreate); -GUEST_FUNCTION_HOOK(sub_8255CC48, XMAPlaybackRequestModifyLock); -GUEST_FUNCTION_HOOK(sub_8255CCC8, XMAPlaybackWaitUntilModifyLockObtained); -GUEST_FUNCTION_HOOK(sub_8255C4D0, XMAPlaybackQueryReadyForMoreData); -GUEST_FUNCTION_HOOK(sub_8255C520, XMAPlaybackIsIdle); -GUEST_FUNCTION_HOOK(sub_8255C388, XMAPlaybackQueryContextsAllocated); -GUEST_FUNCTION_HOOK(sub_8255CF10, XMAPlaybackResumePlayback); -GUEST_FUNCTION_HOOK(sub_8255C470, XMAPlaybackQueryInputDataPending); -GUEST_FUNCTION_HOOK(sub_8255C9A0, XMAPlaybackGetErrorBits); -GUEST_FUNCTION_HOOK(sub_8255C398, XMAPlaybackSubmitData); -GUEST_FUNCTION_HOOK(sub_8255C578, XMAPlaybackQueryAvailableData); -GUEST_FUNCTION_HOOK(sub_8255C7A8, XMAPlaybackAccessDecodedData); -GUEST_FUNCTION_HOOK(sub_8255C5F0, XMAPlaybackConsumeDecodedData); -GUEST_FUNCTION_HOOK(sub_8255CD90, XMAPlaybackQueryModifyLockObtained); -GUEST_FUNCTION_HOOK(sub_8255C8D8, XMAPlaybackFlushData); -GUEST_FUNCTION_HOOK(sub_8255C9D8, XmaPlaybackSetLoop); -GUEST_FUNCTION_HOOK(sub_8255CA50, XMAPlaybackGetRemainingLoopCount); -GUEST_FUNCTION_HOOK(sub_8255CA90, XMAPlaybackGetStreamPosition); -GUEST_FUNCTION_HOOK(sub_8255CB20, XMAPlaybackSetDecodePosition); -GUEST_FUNCTION_HOOK(sub_8255C850, XMAPlaybackRewindDecodePosition); -GUEST_FUNCTION_HOOK(sub_8255CAB0, XMAPlaybackQueryCurrentPosition); -GUEST_FUNCTION_HOOK(sub_8255C2C0, XMAPlaybackDestroy); diff --git a/MarathonRecomp/locale/config_locale.cpp b/MarathonRecomp/locale/config_locale.cpp index ca0877deed..904d428308 100644 --- a/MarathonRecomp/locale/config_locale.cpp +++ b/MarathonRecomp/locale/config_locale.cpp @@ -1063,6 +1063,11 @@ CONFIG_DEFINE_LOCALE(EnableDebugMode) { ELanguage::English, { "Enable Debug Mode", "Enables debug mode to be toggled by pressing the ${picture(button_back)} button." } } }; +CONFIG_DEFINE_LOCALE(FixAudioOuttake) +{ + { ELanguage::English, { "Fix Audio Outtake", "Removes a left-in audio outtake during Shadow's story." } } +}; + CONFIG_DEFINE_LOCALE(FixEnvironmentMaps) { { ELanguage::English, { "Fix Environment Maps", "Fixes the game not loading new environment maps correctly, resulting in mismatching reflections in some areas." } } diff --git a/MarathonRecomp/patches/xma_patches.cpp b/MarathonRecomp/patches/xma_patches.cpp new file mode 100644 index 0000000000..e1c55a2f31 --- /dev/null +++ b/MarathonRecomp/patches/xma_patches.cpp @@ -0,0 +1,343 @@ +#include "user/config.h" + +#include +#include +#include +#include +#include + +// 8192 frames per block, 170 ms at 48 kHz. +static constexpr uint32_t PCM_FRAMES_PER_BLOCK = 8192; +static constexpr uint8_t PCM_MAX_PACKET_COUNT = 3; +static constexpr uint8_t XAUDIO_SAMPLETYPE_16BITPCM = 1; + +struct HostReader +{ + std::shared_ptr m_pcm; + bool m_synthetic{}; // no OS file handle behind the reader +}; + +static std::mutex g_hostReadersMutex; +static std::unordered_map g_hostReaders; // keyed by guest XmaStreamReader address + +struct XmaStreamChunk +{ + be m_FourCC; + xpointer m_pParent; + be m_FileHandle; + be m_DataOffset; + be m_Size; + MARATHON_INSERT_PADDING(0x04); +}; + +MARATHON_ASSERT_SIZEOF(XmaStreamChunk, 0x18); + +struct XmaStreamFormat // header at reader + 0x98, partially known; do not assert a size +{ + MARATHON_INSERT_PADDING(0x03); + uint8_t m_LoopCount; + be m_LoopBegin; + be m_LoopEnd; + MARATHON_INSERT_PADDING(0x04); + be m_BlockSize; + MARATHON_INSERT_PADDING(0x08); + be m_BlockCount; +}; + +struct XmaStreamReader +{ + be m_FileHandle; + XmaStreamChunk m_Riff; + XmaStreamChunk m_Fmt; + XmaStreamChunk m_Data; + XmaStreamChunk m_Wave; + XmaStreamChunk m_Seek; + XmaStreamChunk m_Xma2; + xpointer m_pFmt; + xpointer m_pXma2; + xpointer> m_pSeek; +}; + +MARATHON_ASSERT_SIZEOF(XmaStreamReader, 0xA0); + +static std::shared_ptr FindHostPcm(uint32_t reader) +{ + std::lock_guard lock(g_hostReadersMutex); + + auto it = g_hostReaders.find(reader); + + return it != g_hostReaders.end() ? it->second.m_pcm : nullptr; +} + +static std::optional TakeHostReader(uint32_t reader) +{ + std::lock_guard lock(g_hostReadersMutex); + + auto it = g_hostReaders.find(reader); + + if (it == g_hostReaders.end()) + return std::nullopt; + + auto hostReader = std::move(it->second); + g_hostReaders.erase(it); + + return hostReader; +} + +static void RegisterHostReader(uint32_t reader, std::shared_ptr pcm, bool synthetic) +{ + std::lock_guard lock(g_hostReadersMutex); + + g_hostReaders[reader] = { std::move(pcm), synthetic }; +} + +static void* AllocGuest(size_t size) +{ + void* pMemory = g_userHeap.Alloc(size); + memset(pMemory, 0, size); + + return pMemory; +} + +static void ApplyPcmGeometry(XmaStreamReader* pReader, XmaStreamFormat* pXma2, const std::shared_ptr& pcm) +{ + const uint32_t frameSize = pcm->GetChannels() * sizeof(int16_t); + const uint32_t blockSize = PCM_FRAMES_PER_BLOCK * frameSize; + const uint32_t frames = pcm->GetFrameCount(); + const uint32_t blockCount = std::max(1u, (frames + PCM_FRAMES_PER_BLOCK - 1) / PCM_FRAMES_PER_BLOCK); + + pXma2->m_BlockSize = blockSize; + pXma2->m_BlockCount = blockCount; + + // Cumulative frames per block. The last entry is one past the end so that a loop end + // equal to the file length still matches a block in sub_8238BA40, which compares with + // a strict less-than. + auto* pSeek = static_cast*>(AllocGuest(blockCount * sizeof(be))); + + for (uint32_t i = 0; i < blockCount; i++) + pSeek[i] = std::min((i + 1) * PCM_FRAMES_PER_BLOCK, frames); + + pSeek[blockCount - 1] = frames + 1; + + // The original table came from the same heap, and the reader destroy only frees what is set then. + if (auto* pOldSeek = pReader->m_pSeek.get()) + g_userHeap.Free(pOldSeek); + + pReader->m_pSeek = pSeek; + + // sub_8238B820 clamps block reads against the data chunk size. + pReader->m_Data.m_Size = frames * frameSize; + + // The game re-reads both of these on every block, so a corrected length takes effect immediately. + pcm->SetLengthChangedCallback([pReader, pXma2, frameSize](uint32_t newFrames) + { + pReader->m_Data.m_Size = newFrames * frameSize; + pXma2->m_BlockCount = (newFrames + PCM_FRAMES_PER_BLOCK - 1) / PCM_FRAMES_PER_BLOCK; + }); +} + +static bool InstallSyntheticReader(uint32_t readerAddress, std::shared_ptr pcm) +{ + if (!pcm) + return false; + + auto* pReader = static_cast(g_memory.Translate(readerAddress)); + + const uint32_t channels = pcm->GetChannels(); + const uint32_t streams = channels <= 2 ? 1 : (channels + 1) / 2; + auto* pFmt = static_cast(AllocGuest(0x80)); + + *reinterpret_cast*>(pFmt + 0x08) = static_cast(streams); + *reinterpret_cast*>(pFmt + 0x10) = pcm->GetSampleRate(); + pFmt[0x1D] = static_cast(std::min(channels, 2u)); + + // XMA2 chunk copy, only the fields the game reads. + auto* pXma2 = static_cast(AllocGuest(0x40)); + + pXma2->m_LoopCount = 0; // looping comes from the cue flag + pXma2->m_LoopBegin = pcm->GetLoopBegin(); + pXma2->m_LoopEnd = pcm->GetLoopEnd(); + + ApplyPcmGeometry(pReader, pXma2, pcm); + + // There is no OS file handle, the reader destroy hook resets this before the original runs. + pReader->m_FileHandle = 0; + pReader->m_pFmt = pFmt; + pReader->m_pXma2 = pXma2; + + RegisterHostReader(readerAddress, std::move(pcm), true); + + return true; +} + +struct StartOffset +{ + const char* m_stem; + double m_seconds; +}; + +static constexpr StartOffset START_OFFSETS[] = +{ + { "twn01_e52_gn", 6.75 } +}; + +static std::optional GetStartOffsetSeconds(const std::filesystem::path& path) +{ + const auto stem = path.stem().string(); + + if (Config::FixAudioOuttake) + { + for (auto& entry : START_OFFSETS) + { + if (stem == entry.m_stem) + return entry.m_seconds; + } + } + + return std::nullopt; +} + +static bool InstallStockReader(uint32_t readerAddress, const std::filesystem::path& path) +{ + auto* pReader = static_cast(g_memory.Translate(readerAddress)); + + auto* pXma2 = pReader->m_pXma2.get(); + auto* pSeek = pReader->m_pSeek.get(); + + if (!pXma2 || !pSeek) + return false; + + const uint32_t blockCount = pXma2->m_BlockCount; + const uint32_t blockSize = pXma2->m_BlockSize; + + if (blockCount == 0 || blockSize == 0) + return false; + + HostPcmXmaLayout layout; + layout.m_dataOffset = pReader->m_Data.m_DataOffset; + layout.m_blockSize = blockSize; + + for (uint32_t i = 0; i < blockCount; i++) + layout.m_blockEnds.push_back(pSeek[i]); + + auto pcm = HostPcm::Open(path, std::move(layout)); + + if (!pcm) + return false; + + if (auto seconds = GetStartOffsetSeconds(path)) + { + const uint32_t offset = static_cast(*seconds * pcm->GetSampleRate()); + + pcm->SetStartOffset(offset); + + // The loop points in the XMA2 chunk count from the original start. + auto shift = [offset](uint32_t frame) { return frame > offset ? frame - offset : 0u; }; + + pXma2->m_LoopBegin = shift(pXma2->m_LoopBegin); + pXma2->m_LoopEnd = shift(pXma2->m_LoopEnd); + } + + ApplyPcmGeometry(pReader, pXma2, pcm); + RegisterHostReader(readerAddress, std::move(pcm), false); + + return true; +} + +// Reader destroy and reset +PPC_FUNC_IMPL(__imp__sub_8238B8F0); +PPC_FUNC(sub_8238B8F0) +{ + if (auto hostReader = TakeHostReader(ctx.r3.u32)) + { + hostReader->m_pcm->SetLengthChangedCallback(nullptr); + + if (hostReader->m_synthetic) + static_cast(g_memory.Translate(ctx.r3.u32))->m_FileHandle = 0xFFFFFFFF; + } + + __imp__sub_8238B8F0(ctx, base); +} + +// RIFF Parser +PPC_FUNC_IMPL(__imp__sub_8238BCB8); +PPC_FUNC(sub_8238BCB8) +{ + const uint32_t reader = ctx.r3.u32; + const auto hostPath = FileSystem::ResolvePath(std::string_view(static_cast(g_memory.Translate(ctx.r4.u32))), true); + + __imp__sub_8238BCB8(ctx, base); + + if (ctx.r3.s32 >= 0) + { + InstallStockReader(reader, hostPath); + return; + } + + const uint32_t result = ctx.r3.u32; + + ctx.r3.u32 = reader; + // Reset what the parser left behind + __imp__sub_8238B8F0(ctx, base); + + if (InstallSyntheticReader(reader, HostPcm::Open(hostPath))) + { + ctx.r3.u32 = 0; + return; + } + + ctx.r3.u32 = result; +} + +// ReadChunk +PPC_FUNC_IMPL(__imp__sub_8238B650); +PPC_FUNC(sub_8238B650) +{ + auto pcm = FindHostPcm(ctx.r3.u32 - 0x34); + + if (!pcm) + { + __imp__sub_8238B650(ctx, base); + return; + } + + const uint32_t channels = pcm->GetChannels(); + const uint32_t frameSize = channels * sizeof(int16_t); + const uint32_t size = ctx.r6.u32; + + auto* pDestination = static_cast(g_memory.Translate(ctx.r5.u32)); + + const uint32_t frames = pcm->Read(ctx.r4.u32 / frameSize, size / frameSize, pDestination); + const size_t samples = static_cast(frames) * channels; + + // The guest engine reads its PCM as big-endian 16-bit samples. + for (size_t i = 0; i < samples; i++) + ByteSwapInplace(pDestination[i]); + + // Fill anything extra with silence. + memset(pDestination + samples, 0, size - samples * sizeof(int16_t)); + + ctx.r3.u32 = 0; +} + +// FillVoiceInit +PPC_FUNC_IMPL(__imp__sub_8238B960); +PPC_FUNC(sub_8238B960) +{ + auto pcm = FindHostPcm(ctx.r3.u32); + const uint32_t init = ctx.r4.u32; + + // The original picks the voice routing from the fmt chunk. + __imp__sub_8238B960(ctx, base); + + if (!pcm) + return; + + auto* pInit = static_cast(g_memory.Translate(init)); + + pInit[0x00] = XAUDIO_SAMPLETYPE_16BITPCM; + pInit[0x04] = static_cast(pcm->GetChannels()); + *reinterpret_cast*>(pInit + 0x08) = pcm->GetSampleRate(); + memset(pInit + 0x0C, 0, 0x14); + pInit[0x3B] = PCM_MAX_PACKET_COUNT; +} diff --git a/MarathonRecomp/user/config_def.h b/MarathonRecomp/user/config_def.h index f2ff2286c6..f99dbed5bd 100644 --- a/MarathonRecomp/user/config_def.h +++ b/MarathonRecomp/user/config_def.h @@ -137,6 +137,7 @@ CONFIG_DEFINE_LOCALISED("Codes", bool, E3ChainJumpSpeed, false, false); CONFIG_DEFINE_LOCALISED("Codes", bool, E3CheckpointBehavior, false, false); CONFIG_DEFINE_LOCALISED("Codes", bool, E3RespawnTime, false, false); CONFIG_DEFINE_LOCALISED("Codes", bool, EnableDebugMode, false, false); +CONFIG_DEFINE_LOCALISED("Codes", bool, FixAudioOuttake, false, false); CONFIG_DEFINE_LOCALISED("Codes", bool, FixEnvironmentMaps, true, false); CONFIG_DEFINE_LOCALISED("Codes", bool, FixOmegaShotCollision, false, false); CONFIG_DEFINE_LOCALISED("Codes", bool, FixPowerUpJingleDuration, true, false); diff --git a/docs/BUILDING.md b/docs/BUILDING.md index 3190862ebc..fb15dadfb3 100644 --- a/docs/BUILDING.md +++ b/docs/BUILDING.md @@ -39,18 +39,18 @@ In the installer, you must select the following **Workloads** and **Individual c ### Linux The following command will install the required dependencies on a distro that uses `apt` (such as Debian-based distros). ```bash -sudo apt install pkg-config curl cmake ninja-build clang clang-tools lld llvm libgtk-3-dev +sudo apt install pkg-config curl cmake ninja-build nasm clang clang-tools lld llvm libgtk-3-dev ``` The following command will install the required dependencies on a distro that uses `dnf` (such as Fedora-based distros). Note: The second line of dependencies is to satisfy the vcpkg OpenSSL build. ```bash -sudo dnf install pkg-config curl cmake ninja-build clang lld llvm gtk3-devel \ +sudo dnf install pkg-config curl cmake ninja-build nasm clang lld llvm gtk3-devel \ perl-FindBin perl-IPC-Cmd perl-Time-Piece perl-File-Compare perl-File-Copy ``` The following command will install the required dependencies on a distro that uses `pacman` (such as Arch-based distros). ```bash -sudo pacman -S base-devel ninja lld clang gtk3 +sudo pacman -S base-devel ninja nasm lld clang gtk3 ``` You can also find the equivalent packages for your preferred distro. diff --git a/thirdparty/CMakeLists.txt b/thirdparty/CMakeLists.txt index 193f219da3..127da6a9a6 100644 --- a/thirdparty/CMakeLists.txt +++ b/thirdparty/CMakeLists.txt @@ -46,4 +46,3 @@ add_subdirectory("${MARATHON_RECOMP_THIRDPARTY_ROOT}/o1heap") add_subdirectory("${MARATHON_RECOMP_THIRDPARTY_ROOT}/SDL") add_subdirectory("${MARATHON_RECOMP_THIRDPARTY_ROOT}/SDL_mixer") add_subdirectory("${MARATHON_RECOMP_THIRDPARTY_ROOT}/plume") -add_subdirectory("${MARATHON_RECOMP_THIRDPARTY_ROOT}/ffmpeg-core") diff --git a/thirdparty/ffmpeg-core b/thirdparty/ffmpeg-core deleted file mode 160000 index e5293c050a..0000000000 --- a/thirdparty/ffmpeg-core +++ /dev/null @@ -1 +0,0 @@ -Subproject commit e5293c050a20af3dbbd5114067693e7f7301cdee diff --git a/vcpkg.json b/vcpkg.json index cd65a52805..553473cb0c 100644 --- a/vcpkg.json +++ b/vcpkg.json @@ -9,6 +9,7 @@ "name": "directx12-agility", "platform": "windows" }, + "ffmpeg", "freetype", "curl" ],