codec_abstract_codec.h 9.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344
  1. #pragma once
  2. #include "../base/types.h"
  3. #include <memory>
  4. #include <functional>
  5. #include <vector>
  6. #include <string>
  7. #include <shared_mutex>
  8. #include <mutex>
  9. namespace av {
  10. namespace codec {
  11. /**
  12. * 编解码器状态
  13. */
  14. enum class CodecState {
  15. IDLE, // 空闲
  16. OPENED, // 已打开
  17. RUNNING, // 运行中
  18. FLUSHING, // 刷新中
  19. CLOSED, // 已关闭
  20. ERROR // 错误
  21. };
  22. /**
  23. * 编解码器类型
  24. */
  25. enum class CodecType {
  26. ENCODER, // 编码器
  27. DECODER // 解码器
  28. };
  29. /**
  30. * 抽象编解码器基类
  31. * 提供编解码器的通用接口和状态管理
  32. */
  33. class AbstractCodec {
  34. public:
  35. AbstractCodec(MediaType mediaType, CodecType codecType);
  36. virtual ~AbstractCodec();
  37. // 禁止拷贝
  38. AbstractCodec(const AbstractCodec&) = delete;
  39. AbstractCodec& operator=(const AbstractCodec&) = delete;
  40. /**
  41. * 打开编解码器
  42. * @param params 编解码参数
  43. * @return 成功返回ErrorCode::SUCCESS
  44. */
  45. virtual ErrorCode open(const CodecParams& params) = 0;
  46. /**
  47. * 关闭编解码器
  48. */
  49. virtual void close() = 0;
  50. /**
  51. * 刷新编解码器缓冲区
  52. * @return 成功返回ErrorCode::SUCCESS
  53. */
  54. virtual ErrorCode flush() = 0;
  55. /**
  56. * 重置编解码器
  57. * @return 成功返回ErrorCode::SUCCESS
  58. */
  59. virtual ErrorCode reset();
  60. // 状态查询(线程安全)
  61. CodecState getState() const {
  62. std::shared_lock<std::shared_mutex> lock(stateMutex_);
  63. return state_;
  64. }
  65. MediaType getMediaType() const { return mediaType_; }
  66. CodecType getCodecType() const { return codecType_; }
  67. bool isOpened() const {
  68. std::shared_lock<std::shared_mutex> lock(stateMutex_);
  69. return state_ == CodecState::OPENED || state_ == CodecState::RUNNING;
  70. }
  71. bool isRunning() const {
  72. std::shared_lock<std::shared_mutex> lock(stateMutex_);
  73. return state_ == CodecState::RUNNING;
  74. }
  75. bool hasError() const {
  76. std::shared_lock<std::shared_mutex> lock(stateMutex_);
  77. return state_ == CodecState::ERROR;
  78. }
  79. // 参数获取
  80. const CodecParams& getParams() const { return params_; }
  81. // 统计信息
  82. struct Statistics {
  83. uint64_t processedFrames = 0; // 处理的帧数
  84. uint64_t droppedFrames = 0; // 丢弃的帧数
  85. uint64_t errorCount = 0; // 错误次数
  86. double avgProcessTime = 0.0; // 平均处理时间(ms)
  87. uint64_t totalBytes = 0; // 总字节数
  88. };
  89. Statistics getStatistics() const {
  90. std::lock_guard<std::mutex> lock(statsMutex_);
  91. return stats_;
  92. }
  93. void resetStatistics();
  94. // 回调函数设置
  95. using ErrorCallback = std::function<void(ErrorCode error, const std::string& message)>;
  96. void setErrorCallback(ErrorCallback callback) { errorCallback_ = std::move(callback); }
  97. // 错误码转换工具
  98. static ErrorCode convertFFmpegError(int ffmpegError);
  99. static std::string getErrorDescription(ErrorCode error);
  100. protected:
  101. // RAII资源管理包装器
  102. template<typename T, typename Deleter>
  103. class ResourceGuard {
  104. private:
  105. T* resource_;
  106. Deleter deleter_;
  107. bool released_;
  108. public:
  109. explicit ResourceGuard(T* resource, Deleter deleter)
  110. : resource_(resource), deleter_(deleter), released_(false) {}
  111. ~ResourceGuard() {
  112. if (!released_ && resource_) {
  113. deleter_(resource_);
  114. }
  115. }
  116. // 禁止拷贝
  117. ResourceGuard(const ResourceGuard&) = delete;
  118. ResourceGuard& operator=(const ResourceGuard&) = delete;
  119. // 允许移动
  120. ResourceGuard(ResourceGuard&& other) noexcept
  121. : resource_(other.resource_), deleter_(std::move(other.deleter_)), released_(other.released_) {
  122. other.released_ = true;
  123. }
  124. ResourceGuard& operator=(ResourceGuard&& other) noexcept {
  125. if (this != &other) {
  126. if (!released_ && resource_) {
  127. deleter_(resource_);
  128. }
  129. resource_ = other.resource_;
  130. deleter_ = std::move(other.deleter_);
  131. released_ = other.released_;
  132. other.released_ = true;
  133. }
  134. return *this;
  135. }
  136. T* get() const { return resource_; }
  137. T* release() { released_ = true; return resource_; }
  138. void reset(T* newResource = nullptr) {
  139. if (!released_ && resource_) {
  140. deleter_(resource_);
  141. }
  142. resource_ = newResource;
  143. released_ = false;
  144. }
  145. explicit operator bool() const { return resource_ != nullptr && !released_; }
  146. };
  147. // 状态管理助手,确保状态一致性
  148. class StateGuard {
  149. private:
  150. AbstractCodec* codec_;
  151. CodecState originalState_;
  152. CodecState targetState_;
  153. bool committed_;
  154. public:
  155. StateGuard(AbstractCodec* codec, CodecState targetState)
  156. : codec_(codec), targetState_(targetState), committed_(false) {
  157. if (codec_) {
  158. originalState_ = codec_->getState();
  159. codec_->setState(targetState_);
  160. }
  161. }
  162. ~StateGuard() {
  163. if (!committed_ && codec_) {
  164. codec_->setState(originalState_);
  165. }
  166. }
  167. void commit() { committed_ = true; }
  168. // 禁止拷贝和移动
  169. StateGuard(const StateGuard&) = delete;
  170. StateGuard& operator=(const StateGuard&) = delete;
  171. StateGuard(StateGuard&&) = delete;
  172. StateGuard& operator=(StateGuard&&) = delete;
  173. };
  174. /**
  175. * 设置编解码器状态
  176. */
  177. void setState(CodecState state);
  178. /**
  179. * 报告错误
  180. */
  181. void reportError(ErrorCode error, const std::string& message = "");
  182. /**
  183. * 更新统计信息
  184. */
  185. void updateStats(bool success, double processTime, uint64_t bytes = 0);
  186. /**
  187. * 验证参数有效性
  188. */
  189. virtual bool validateParams(const CodecParams& params) = 0;
  190. protected:
  191. MediaType mediaType_; // 媒体类型
  192. CodecType codecType_; // 编解码器类型
  193. CodecState state_; // 当前状态
  194. CodecParams params_; // 编解码参数
  195. Statistics stats_; // 统计信息
  196. ErrorCallback errorCallback_; // 错误回调
  197. // FFmpeg相关
  198. AVCodecContextPtr codecCtx_; // 编解码上下文
  199. const AVCodec* codec_; // 编解码器
  200. // 线程安全机制
  201. mutable std::shared_mutex stateMutex_; // 状态读写锁
  202. mutable std::mutex statsMutex_; // 统计信息锁
  203. mutable std::mutex resourceMutex_; // 资源操作锁
  204. };
  205. /**
  206. * 抽象编码器基类
  207. */
  208. class AbstractEncoder : public AbstractCodec {
  209. public:
  210. AbstractEncoder(MediaType mediaType) : AbstractCodec(mediaType, CodecType::ENCODER) {}
  211. virtual ~AbstractEncoder() = default;
  212. /**
  213. * 编码一帧数据
  214. * @param frame 输入帧
  215. * @param packets 输出包列表
  216. * @return 成功返回ErrorCode::SUCCESS
  217. */
  218. virtual ErrorCode encode(const AVFramePtr& frame, std::vector<AVPacketPtr>& packets) = 0;
  219. /**
  220. * 结束编码(刷新缓冲区)
  221. * @param packets 输出包列表
  222. * @return 成功返回ErrorCode::SUCCESS
  223. */
  224. virtual ErrorCode finishEncode(std::vector<AVPacketPtr>& packets) = 0;
  225. // 编码器特有的回调
  226. using FrameCallback = std::function<void(const AVFramePtr& frame)>;
  227. using PacketCallback = std::function<void(const AVPacketPtr& packet)>;
  228. void setFrameCallback(FrameCallback callback) { frameCallback_ = std::move(callback); }
  229. void setPacketCallback(PacketCallback callback) { packetCallback_ = std::move(callback); }
  230. protected:
  231. FrameCallback frameCallback_; // 帧回调
  232. PacketCallback packetCallback_; // 包回调
  233. };
  234. /**
  235. * 抽象解码器基类
  236. */
  237. class AbstractDecoder : public AbstractCodec {
  238. public:
  239. AbstractDecoder(MediaType mediaType) : AbstractCodec(mediaType, CodecType::DECODER) {}
  240. virtual ~AbstractDecoder() = default;
  241. /**
  242. * 解码一个包
  243. * @param packet 输入包
  244. * @param frames 输出帧列表
  245. * @return 成功返回ErrorCode::SUCCESS
  246. */
  247. virtual ErrorCode decode(const AVPacketPtr& packet, std::vector<AVFramePtr>& frames) = 0;
  248. /**
  249. * 结束解码(刷新缓冲区)
  250. * @param frames 输出帧列表
  251. * @return 成功返回ErrorCode::SUCCESS
  252. */
  253. virtual ErrorCode finishDecode(std::vector<AVFramePtr>& frames) = 0;
  254. // 解码器特有的回调
  255. using PacketCallback = std::function<void(const AVPacketPtr& packet)>;
  256. using FrameCallback = std::function<void(const AVFramePtr& frame)>;
  257. void setPacketCallback(PacketCallback callback) { packetCallback_ = std::move(callback); }
  258. void setFrameCallback(FrameCallback callback) { frameCallback_ = std::move(callback); }
  259. protected:
  260. PacketCallback packetCallback_; // 包回调
  261. FrameCallback frameCallback_; // 帧回调
  262. };
  263. /**
  264. * 编解码器工厂类
  265. */
  266. class CodecFactory {
  267. public:
  268. /**
  269. * 创建编码器
  270. */
  271. static std::unique_ptr<AbstractEncoder> createEncoder(MediaType mediaType, const std::string& codecName);
  272. /**
  273. * 创建解码器
  274. */
  275. static std::unique_ptr<AbstractDecoder> createDecoder(MediaType mediaType, const std::string& codecName);
  276. /**
  277. * 获取支持的编码器列表
  278. */
  279. static std::vector<std::string> getSupportedEncoders(MediaType mediaType);
  280. /**
  281. * 获取支持的解码器列表
  282. */
  283. static std::vector<std::string> getSupportedDecoders(MediaType mediaType);
  284. /**
  285. * 检查编解码器是否支持
  286. */
  287. static bool isCodecSupported(const std::string& codecName, CodecType type, MediaType mediaType);
  288. };
  289. } // namespace codec
  290. } // namespace av