Files
faumaray 5c036d91fb making WEB
Signed-off-by: faumaray <faumaray@gmail.com>
2026-07-11 00:45:17 +03:00

149 lines
4.9 KiB
C++

#pragma once
#include "NetworkTypes.hpp"
#include <AudioTypes.hpp>
#include <Types.hpp>
#include <atomic>
#include <condition_variable>
#include <deque>
#include <mutex>
#include <optional>
#include <thread>
#include <vector>
// Forward declarations for FFmpeg
extern "C" {
struct AVFormatContext;
struct AVCodecContext;
struct AVFrame;
struct AVPacket;
struct SwrContext;
}
namespace Echoion::Core
{
// FFmpeg-backed streaming decoder. openSource() spawns a decode jthread
// that resamples to interleaved S16 at the configured output format and
// fills int16Queue_ (bounded, backpressured); the playback side drains it
// chunk-by-chunk via getNextChunk().
class AudioDecoder
{
public:
AudioDecoder();
~AudioDecoder();
Api::Result<void> initialize();
void shutdown();
// Open audio source (URL or file path)
Api::Result<void> openSource(const std::string& url);
void closeSource();
// Seek to position
Api::Result<void> seek(std::chrono::milliseconds position);
// Get audio info
[[nodiscard]] Api::Result<Api::AudioStreamInfo>
getStreamInfo() const;
// Get current decode position (runs ahead of playback by up to
// the queued chunk depth; use MusicManager for playback position)
[[nodiscard]] std::chrono::milliseconds getPosition() const;
// Set output format
void setOutputFormat(uint32_t sampleRate, uint32_t channels);
// Set proxy configuration for network requests
void setProxyConfig(const std::optional<Void::Net::ProxyConfig>& proxy);
// Get next S16 chunk. Swaps the caller's buffer for the queued
// one, so the caller's previous storage is recycled into the
// decode free-list — no per-chunk copy or allocation.
bool getNextChunk(std::vector<int16_t>& outChunk,
bool blocking = false);
// Check if decode is finished
[[nodiscard]] bool isFinished() const { return eof_.load(); }
// Decoded audio waiting in the queue, in interleaved S16 samples.
// The crossfade readiness gate uses this: a fade only starts once
// the incoming decoder has buffered enough audio to survive it.
[[nodiscard]] std::size_t queuedSamples() const;
// True when the decode queue is at capacity (the decode thread is
// backpressured) — waiting longer cannot buffer any more.
[[nodiscard]] bool queueSaturated() const;
private:
void decodeThread();
// One read→decode→flush pass over the source; returns on EOF or
// shutdown. decodeThread() parks between sessions awaiting a
// seek request, so a post-EOF seek resumes decoding.
void decodeSession();
// Perform a pending seek request on the decode thread (the only
// thread allowed to touch the FFmpeg contexts while decoding).
// Returns true if a request was consumed.
bool consumePendingSeek();
// Borrow a chunk buffer of `samples` length from the recycle
// free-list (reusing pooled storage), or allocate one if the
// free-list is empty.
std::vector<int16_t> acquireChunkBuffer(size_t samples);
void cleanupFfmpeg();
// FFmpeg contexts
AVFormatContext* formatContext_ = nullptr;
AVCodecContext* codecContext_ = nullptr;
AVFrame* frame_ = nullptr;
AVPacket* packet_ = nullptr;
SwrContext* swrContext_ = nullptr;
uint8_t* outputBuffer_ = nullptr; // For S16 output like reference
// Stream info
int audioStreamIndex_ = -1;
Api::AudioStreamInfo streamInfo_;
// Output format
uint32_t outputSampleRate_ = 192000;
uint32_t outputChannels_ = 2;
// Threading
std::jthread decodeThread_;
mutable std::mutex mutex_;
std::condition_variable cv_;
// S16 audio queue (like reference) - avoids float conversion
std::deque<std::vector<int16_t>> int16Queue_;
static constexpr size_t MAX_INT16_QUEUE_SIZE = 100;
// Max samples per swr_convert() output call; outputBuffer_ is
// sized for this.
static constexpr int MAX_OUT_SAMPLES = 4096;
// Free-list of recycled chunk buffers. getNextChunk() swaps the
// caller's previous buffer in here and decodeThread() reuses that
// storage instead of allocating a fresh vector per frame.
// Guarded by mutex_ (same as int16Queue_).
std::vector<std::vector<int16_t>> recycledChunks_;
// State
std::atomic<bool> initialized_{false};
std::atomic<bool> decoding_{false};
std::atomic<bool> eof_{false};
std::atomic<bool> shouldExit_{
false}; // For FFmpeg interrupt callback
// Decode position in ms; written by the decode thread per frame,
// read cross-thread by getPosition() (prefetch decisions).
std::atomic<int64_t> currentPositionMs_{0};
// Pending seek target in ms, -1 = none. Written by seek() under
// mutex_ (coordinated with eof_), consumed by the decode thread.
std::atomic<int64_t> seekRequestMs_{-1};
std::string currentUrl_;
std::atomic<uint32_t> streamSampleRate_{48000};
std::optional<Void::Net::ProxyConfig> proxyConfig_;
};
} // namespace Echoion::Core