56 lines
1.6 KiB
C++
56 lines
1.6 KiB
C++
#pragma once
|
|
#include <atomic>
|
|
#include <condition_variable>
|
|
#include <deque>
|
|
#include <iostream>
|
|
#include <stdexcept>
|
|
#include <string>
|
|
#include <thread>
|
|
#include <vector>
|
|
|
|
extern "C" {
|
|
#include <libavcodec/avcodec.h>
|
|
#include <libavformat/avformat.h>
|
|
#include <libavutil/opt.h>
|
|
#include <libswresample/swresample.h>
|
|
}
|
|
enum class DecodeStatus { Idle, Processing, Completed, Failed, Cancelled };
|
|
class AudioDecoder {
|
|
public:
|
|
struct AudioData {
|
|
std::vector<short> buffer;
|
|
int samples = 0;
|
|
int channels = 0;
|
|
int sampleRate = 0;
|
|
};
|
|
std::deque<std::vector<short>> m_chunkQueue;
|
|
std::mutex m_queueMtx;
|
|
std::condition_variable m_cv;
|
|
std::atomic<bool> m_isDecodingFinished{false};
|
|
AudioDecoder();
|
|
~AudioDecoder();
|
|
void StartDecode(const std::string &url, int targetSampleRate);
|
|
void Cancel() { m_cancelRequested = true; }
|
|
DecodeStatus GetStatus() const { return m_status; }
|
|
AudioData GetResult() { return std::move(m_result); }
|
|
bool GetNextChunk(std::vector<short> &outChunk, bool blocking = false);
|
|
bool IsFinished() const { return m_finished.load(); }
|
|
|
|
private:
|
|
void Log(const std::string &msg) {
|
|
std::lock_guard<std::mutex> lock(m_logMtx);
|
|
std::cout << "[AudioDecoder] " << msg << std::endl;
|
|
}
|
|
void Cleanup();
|
|
void InternalDecode(std::string url, int targetSampleRate);
|
|
std::atomic<DecodeStatus> m_status{DecodeStatus::Idle};
|
|
std::atomic<bool> m_cancelRequested{false};
|
|
std::jthread m_thread;
|
|
std::mutex m_logMtx;
|
|
AudioData m_result;
|
|
std::atomic<bool> m_finished{false};
|
|
AVFormatContext *m_formatCtx = nullptr;
|
|
AVCodecContext *m_codecCtx = nullptr;
|
|
SwrContext *m_swrCtx = nullptr;
|
|
};
|