#pragma once #include "NetworkTypes.hpp" #include #include #include #include #include #include #include #include #include // 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 initialize(); void shutdown(); // Open audio source (URL or file path) Api::Result openSource(const std::string& url); void closeSource(); // Seek to position Api::Result seek(std::chrono::milliseconds position); // Get audio info [[nodiscard]] Api::Result 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& 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& 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 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> 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> recycledChunks_; // State std::atomic initialized_{false}; std::atomic decoding_{false}; std::atomic eof_{false}; std::atomic 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 currentPositionMs_{0}; // Pending seek target in ms, -1 = none. Written by seek() under // mutex_ (coordinated with eof_), consumed by the decode thread. std::atomic seekRequestMs_{-1}; std::string currentUrl_; std::atomic streamSampleRate_{48000}; std::optional proxyConfig_; }; } // namespace Echoion::Core