codec_video_decoder.cpp 22 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685
  1. #include "codec_video_decoder.h"
  2. #include "../base/logger.h"
  3. #include "../base/media_common.h"
  4. #include <algorithm>
  5. #include <sstream>
  6. #include <thread>
  7. extern "C" {
  8. #include <libavcodec/avcodec.h>
  9. #include <libavutil/hwcontext.h>
  10. #include <libavutil/pixdesc.h>
  11. #include <libavutil/opt.h>
  12. #include <libswscale/swscale.h>
  13. }
  14. namespace av {
  15. namespace codec {
  16. // 静态成员初始化
  17. std::vector<std::string> VideoDecoder::supportedDecoders_;
  18. std::once_flag VideoDecoder::decodersInitFlag_;
  19. VideoDecoder::VideoDecoder() : AbstractDecoder(MediaType::VIDEO) {
  20. AV_LOGGER_DEBUG("创建视频解码器");
  21. }
  22. VideoDecoder::~VideoDecoder() {
  23. close();
  24. AV_LOGGER_DEBUG("视频解码器已销毁");
  25. }
  26. ErrorCode VideoDecoder::initialize(const CodecParams& params) {
  27. if (params.type != MediaType::VIDEO) {
  28. AV_LOGGER_ERROR("参数类型不是视频");
  29. return ErrorCode::INVALID_PARAMS;
  30. }
  31. videoParams_ = static_cast<const VideoDecoderParams&>(params);
  32. if (!validateParams(params)) {
  33. return ErrorCode::INVALID_PARAMS;
  34. }
  35. setState(CodecState::IDLE);
  36. AV_LOGGER_INFOF("视频解码器初始化成功: {}", videoParams_.codecName);
  37. return ErrorCode::SUCCESS;
  38. }
  39. ErrorCode VideoDecoder::setStreamParameters(const AVCodecParameters* codecpar) {
  40. if (!codecpar) {
  41. AV_LOGGER_ERROR("流参数为空");
  42. return ErrorCode::INVALID_PARAMS;
  43. }
  44. if (codecpar->codec_type != AVMEDIA_TYPE_VIDEO) {
  45. AV_LOGGER_ERROR("流类型不是视频");
  46. return ErrorCode::INVALID_PARAMS;
  47. }
  48. // 保存流参数以便后续使用
  49. streamCodecpar_ = codecpar;
  50. AV_LOGGER_INFOF("设置流参数: 编解码器ID={}, 尺寸={}x{}, 格式={}",
  51. static_cast<int>(codecpar->codec_id),
  52. codecpar->width, codecpar->height,
  53. static_cast<int>(codecpar->format));
  54. return ErrorCode::SUCCESS;
  55. }
  56. ErrorCode VideoDecoder::open(const CodecParams& params) {
  57. std::lock_guard<std::mutex> lock(decodeMutex_);
  58. // 如果提供了参数,先初始化
  59. if (params.type != MediaType::UNKNOWN) {
  60. ErrorCode initResult = initialize(params);
  61. if (initResult != ErrorCode::SUCCESS) {
  62. return initResult;
  63. }
  64. }
  65. if (state_ != CodecState::IDLE) {
  66. AV_LOGGER_ERROR("解码器状态无效,无法打开");
  67. return ErrorCode::INVALID_STATE;
  68. }
  69. ErrorCode result = initDecoder();
  70. if (result != ErrorCode::SUCCESS) {
  71. return result;
  72. }
  73. setState(CodecState::OPENED);
  74. AV_LOGGER_INFOF("视频解码器已打开: {} ({}x{})",
  75. videoParams_.codecName,
  76. codecCtx_->width, codecCtx_->height);
  77. return ErrorCode::SUCCESS;
  78. }
  79. void VideoDecoder::close() {
  80. std::lock_guard<std::mutex> lock(decodeMutex_);
  81. if (state_ == CodecState::IDLE) {
  82. return;
  83. }
  84. // 清理硬件资源
  85. if (hwDeviceCtx_) {
  86. av_buffer_unref(&hwDeviceCtx_);
  87. hwDeviceCtx_ = nullptr;
  88. }
  89. hwFrame_.reset();
  90. codecCtx_.reset();
  91. codec_ = nullptr;
  92. isHardwareDecoder_ = false;
  93. setState(CodecState::IDLE);
  94. AV_LOGGER_DEBUG("视频解码器已关闭");
  95. }
  96. ErrorCode VideoDecoder::flush() {
  97. std::lock_guard<std::mutex> lock(decodeMutex_);
  98. if (state_ != CodecState::OPENED && state_ != CodecState::RUNNING) {
  99. return ErrorCode::INVALID_STATE;
  100. }
  101. if (codecCtx_) {
  102. avcodec_flush_buffers(codecCtx_.get());
  103. // 视频解码器flush完成,解码器状态已重置
  104. AV_LOGGER_DEBUG("视频解码器缓冲区已清空");
  105. }
  106. setState(CodecState::OPENED);
  107. AV_LOGGER_DEBUG("视频解码器已重置");
  108. return ErrorCode::SUCCESS;
  109. }
  110. ErrorCode VideoDecoder::reset() {
  111. return flush();
  112. }
  113. ErrorCode VideoDecoder::decode(const AVPacketPtr& packet, std::vector<AVFramePtr>& frames) {
  114. std::lock_guard<std::mutex> lock(decodeMutex_);
  115. if (state_ != CodecState::OPENED && state_ != CodecState::RUNNING) {
  116. return ErrorCode::INVALID_STATE;
  117. }
  118. setState(CodecState::RUNNING);
  119. auto startTime = std::chrono::high_resolution_clock::now();
  120. ErrorCode result = decodeFrame(packet, frames);
  121. auto endTime = std::chrono::high_resolution_clock::now();
  122. double processTime = std::chrono::duration<double, std::milli>(endTime - startTime).count();
  123. updateStats(result == ErrorCode::SUCCESS, processTime,
  124. packet ? packet->size : 0);
  125. if (frameCallback_) {
  126. for (const auto& frame : frames) {
  127. frameCallback_(frame);
  128. }
  129. }
  130. return result;
  131. }
  132. ErrorCode VideoDecoder::finishDecode(std::vector<AVFramePtr>& frames) {
  133. return decode(nullptr, frames); // 发送空包来刷新解码器
  134. }
  135. bool VideoDecoder::validateParams(const CodecParams& params) {
  136. if (params.type != MediaType::VIDEO) {
  137. AV_LOGGER_ERROR("参数媒体类型不是视频");
  138. return false;
  139. }
  140. const auto& videoParams = static_cast<const VideoDecoderParams&>(params);
  141. if (videoParams.codecName.empty()) {
  142. AV_LOGGER_ERROR("解码器名称为空");
  143. return false;
  144. }
  145. return true;
  146. }
  147. ErrorCode VideoDecoder::initDecoder() {
  148. // 查找解码器
  149. codec_ = avcodec_find_decoder_by_name(videoParams_.codecName.c_str());
  150. if (!codec_) {
  151. AV_LOGGER_ERRORF("未找到解码器: {}", videoParams_.codecName);
  152. return ErrorCode::CODEC_NOT_FOUND;
  153. }
  154. if (codec_->type != AVMEDIA_TYPE_VIDEO) {
  155. AV_LOGGER_ERROR("解码器类型不是视频");
  156. return ErrorCode::INVALID_PARAMS;
  157. }
  158. // 创建解码上下文
  159. codecCtx_ = makeAVCodecContext(codec_);
  160. if (!codecCtx_) {
  161. AV_LOGGER_ERROR("分配解码上下文失败");
  162. return ErrorCode::MEMORY_ALLOC_FAILED;
  163. }
  164. // 如果有流参数,复制到解码器上下文
  165. if (streamCodecpar_) {
  166. int ret = avcodec_parameters_to_context(codecCtx_.get(), streamCodecpar_);
  167. if (ret < 0) {
  168. AV_LOGGER_ERRORF("复制流参数到解码器上下文失败: {}", ffmpeg_utils::errorToString(ret));
  169. return static_cast<ErrorCode>(ret);
  170. }
  171. AV_LOGGER_INFO("成功复制流参数到解码器上下文");
  172. }
  173. // 设置硬件加速
  174. if (videoParams_.hardwareAccel && isHardwareDecoder(videoParams_.codecName)) {
  175. ErrorCode result = setupHardwareAcceleration();
  176. if (result != ErrorCode::SUCCESS) {
  177. AV_LOGGER_WARNING("硬件加速设置失败,回退到软件解码");
  178. isHardwareDecoder_ = false;
  179. // 清理硬件资源
  180. if (hwDeviceCtx_) {
  181. av_buffer_unref(&hwDeviceCtx_);
  182. hwDeviceCtx_ = nullptr;
  183. }
  184. }
  185. }
  186. // 设置解码器参数
  187. ErrorCode result = setupDecoderParams();
  188. if (result != ErrorCode::SUCCESS) {
  189. return result;
  190. }
  191. // 打开解码器前的详细日志
  192. AV_LOGGER_INFOF("准备打开解码器: {}", videoParams_.codecName);
  193. AV_LOGGER_INFOF("解码器参数: 线程数: {}, 像素格式: {}",
  194. codecCtx_->thread_count,
  195. static_cast<int>(codecCtx_->pix_fmt));
  196. if (isHardwareDecoder_) {
  197. AV_LOGGER_INFOF("硬件解码器状态: 设备上下文={}",
  198. hwDeviceCtx_ ? "已创建" : "未创建");
  199. }
  200. // 打开解码器
  201. int ret = avcodec_open2(codecCtx_.get(), codec_, nullptr);
  202. if (ret < 0) {
  203. AV_LOGGER_ERRORF("打开解码器失败: {} (错误码: {})",
  204. ffmpeg_utils::errorToString(ret), ret);
  205. // 详细错误分析
  206. if (ret == AVERROR(EINVAL)) {
  207. AV_LOGGER_ERROR("解码器参数无效 - 可能的原因:");
  208. AV_LOGGER_ERROR(" 1. 不支持的像素格式或参数组合");
  209. AV_LOGGER_ERROR(" 2. 硬件解码器参数配置错误");
  210. AV_LOGGER_ERROR(" 3. 硬件设备上下文与解码器不匹配");
  211. } else if (ret == AVERROR(EBUSY)) {
  212. AV_LOGGER_ERROR("硬件设备忙碌 - 可能被其他进程占用");
  213. } else if (ret == AVERROR(ENOMEM)) {
  214. AV_LOGGER_ERROR("内存不足 - 无法分配解码器资源");
  215. }
  216. return static_cast<ErrorCode>(ret);
  217. }
  218. AV_LOGGER_INFOF("解码器打开成功: {}", videoParams_.codecName);
  219. return ErrorCode::SUCCESS;
  220. }
  221. ErrorCode VideoDecoder::setupDecoderParams() {
  222. // 设置视频尺寸
  223. if (videoParams_.width > 0 && videoParams_.height > 0) {
  224. codecCtx_->width = videoParams_.width;
  225. codecCtx_->height = videoParams_.height;
  226. AV_LOGGER_INFOF("设置视频尺寸: {}x{}", videoParams_.width, videoParams_.height);
  227. }
  228. // 设置像素格式(如果指定)
  229. if (videoParams_.pixelFormat != AV_PIX_FMT_NONE) {
  230. codecCtx_->pix_fmt = videoParams_.pixelFormat;
  231. AV_LOGGER_INFOF("设置像素格式: {}", static_cast<int>(videoParams_.pixelFormat));
  232. }
  233. // 设置线程数
  234. if (videoParams_.threadCount > 0) {
  235. codecCtx_->thread_count = videoParams_.threadCount;
  236. } else {
  237. codecCtx_->thread_count = std::min(static_cast<int>(std::thread::hardware_concurrency()), 8);
  238. }
  239. AV_LOGGER_INFOF("设置解码线程数: {}", codecCtx_->thread_count);
  240. // 设置解码器类型
  241. codecCtx_->codec_type = AVMEDIA_TYPE_VIDEO;
  242. // 低延迟设置
  243. if (videoParams_.lowLatency) {
  244. codecCtx_->flags |= AV_CODEC_FLAG_LOW_DELAY;
  245. codecCtx_->flags2 |= AV_CODEC_FLAG2_FAST;
  246. AV_LOGGER_INFO("启用低延迟模式");
  247. }
  248. // 针对不同解码器设置特定参数
  249. if (videoParams_.codecName.find("cuvid") != std::string::npos) {
  250. // NVIDIA CUVID 特定参数
  251. if (codecCtx_->priv_data) {
  252. av_opt_set_int(codecCtx_->priv_data, "surfaces", 8, 0);
  253. if (videoParams_.lowLatency) {
  254. av_opt_set_int(codecCtx_->priv_data, "delay", 0, 0);
  255. }
  256. }
  257. } else if (videoParams_.codecName.find("qsv") != std::string::npos) {
  258. // Intel QSV 特定参数
  259. if (videoParams_.lowLatency && codecCtx_->priv_data) {
  260. av_opt_set(codecCtx_->priv_data, "async_depth", "1", 0);
  261. }
  262. }
  263. AV_LOGGER_INFOF("解码器参数设置完成: 尺寸={}x{}, 格式={}, 线程数={}",
  264. codecCtx_->width, codecCtx_->height,
  265. static_cast<int>(codecCtx_->pix_fmt), codecCtx_->thread_count);
  266. return ErrorCode::SUCCESS;
  267. }
  268. ErrorCode VideoDecoder::setupHardwareAcceleration() {
  269. isHardwareDecoder_ = true;
  270. AVHWDeviceType hwType = getHardwareDeviceType();
  271. if (hwType == AV_HWDEVICE_TYPE_NONE) {
  272. AV_LOGGER_ERRORF("不支持的硬件解码器: {}", videoParams_.codecName);
  273. return ErrorCode::NOT_SUPPORTED;
  274. }
  275. AV_LOGGER_INFOF("开始设置硬件加速: 解码器={}, 设备类型={}",
  276. videoParams_.codecName, static_cast<int>(hwType));
  277. // 创建硬件设备上下文
  278. AV_LOGGER_INFO("创建硬件设备上下文...");
  279. int ret = av_hwdevice_ctx_create(&hwDeviceCtx_, hwType, nullptr, nullptr, 0);
  280. if (ret < 0) {
  281. AV_LOGGER_ERRORF("创建硬件设备上下文失败: {} (解码器: {}, 错误码: {})",
  282. ffmpeg_utils::errorToString(ret), videoParams_.codecName, ret);
  283. // 特定错误处理
  284. if (ret == AVERROR(ENOENT)) {
  285. AV_LOGGER_ERROR("硬件设备不存在或驱动未安装");
  286. if (hwType == AV_HWDEVICE_TYPE_CUDA) {
  287. AV_LOGGER_ERROR("请检查NVIDIA驱动和CUDA是否正确安装");
  288. }
  289. } else if (ret == AVERROR(EBUSY)) {
  290. AV_LOGGER_ERROR("硬件设备正在被其他进程使用");
  291. } else if (ret == AVERROR(EINVAL)) {
  292. AV_LOGGER_ERROR("硬件设备参数无效");
  293. } else if (ret == AVERROR(ENOMEM)) {
  294. AV_LOGGER_ERROR("内存不足,无法创建硬件设备上下文");
  295. }
  296. return static_cast<ErrorCode>(ret);
  297. }
  298. AV_LOGGER_INFOF("硬件设备上下文创建成功: {}", videoParams_.codecName);
  299. // 设置硬件设备上下文到解码器
  300. codecCtx_->hw_device_ctx = av_buffer_ref(hwDeviceCtx_);
  301. return ErrorCode::SUCCESS;
  302. }
  303. ErrorCode VideoDecoder::decodeFrame(const AVPacketPtr& packet, std::vector<AVFramePtr>& frames) {
  304. // 发送包到解码器
  305. int ret = avcodec_send_packet(codecCtx_.get(), packet ? packet.get() : nullptr);
  306. if (ret < 0 && ret != AVERROR_EOF) {
  307. AV_LOGGER_ERRORF("发送包到解码器失败: {}", ffmpeg_utils::errorToString(ret));
  308. return static_cast<ErrorCode>(ret);
  309. }
  310. // 接收解码后的帧
  311. return receiveFrames(frames);
  312. }
  313. ErrorCode VideoDecoder::receiveFrames(std::vector<AVFramePtr>& frames) {
  314. while (true) {
  315. AVFramePtr frame = makeAVFrame();
  316. if (!frame) {
  317. return ErrorCode::MEMORY_ALLOC_FAILED;
  318. }
  319. int ret = avcodec_receive_frame(codecCtx_.get(), frame.get());
  320. if (ret == AVERROR(EAGAIN) || ret == AVERROR_EOF) {
  321. break; // 需要更多输入或已结束
  322. }
  323. if (ret < 0) {
  324. AV_LOGGER_ERRORF("接收解码帧失败: {}", ffmpeg_utils::errorToString(ret));
  325. return static_cast<ErrorCode>(ret);
  326. }
  327. // 处理硬件帧
  328. AVFramePtr processedFrame;
  329. if (isHardwareDecoder_) {
  330. processedFrame = transferFromHardware(std::move(frame));
  331. if (!processedFrame) {
  332. AV_LOGGER_ERROR("硬件帧传输失败");
  333. continue;
  334. }
  335. } else {
  336. processedFrame = std::move(frame);
  337. }
  338. // 格式转换(如果需要)
  339. auto convertedFrame = convertFrame(processedFrame);
  340. if (convertedFrame) {
  341. frames.push_back(std::move(convertedFrame));
  342. } else {
  343. frames.push_back(std::move(processedFrame));
  344. }
  345. }
  346. return ErrorCode::SUCCESS;
  347. }
  348. AVFramePtr VideoDecoder::convertFrame(const AVFramePtr& frame) {
  349. if (!frame) {
  350. return nullptr;
  351. }
  352. // 如果格式已经匹配,直接返回
  353. if (frame->format == videoParams_.pixelFormat) {
  354. return nullptr; // 不需要转换,返回nullptr表示使用原帧
  355. }
  356. // 创建转换后的帧
  357. AVFramePtr convertedFrame = makeAVFrame();
  358. if (!convertedFrame) {
  359. return nullptr;
  360. }
  361. convertedFrame->format = videoParams_.pixelFormat;
  362. convertedFrame->width = frame->width;
  363. convertedFrame->height = frame->height;
  364. if (av_frame_get_buffer(convertedFrame.get(), 32) < 0) {
  365. AV_LOGGER_ERROR("分配转换帧缓冲区失败");
  366. return nullptr;
  367. }
  368. // 使用 swscale 进行格式转换
  369. SwsContext* swsCtx = sws_getContext(
  370. frame->width, frame->height, static_cast<AVPixelFormat>(frame->format),
  371. convertedFrame->width, convertedFrame->height, videoParams_.pixelFormat,
  372. SWS_BILINEAR, nullptr, nullptr, nullptr
  373. );
  374. if (!swsCtx) {
  375. AV_LOGGER_ERROR("创建像素格式转换上下文失败");
  376. return nullptr;
  377. }
  378. sws_scale(swsCtx, frame->data, frame->linesize, 0, frame->height,
  379. convertedFrame->data, convertedFrame->linesize);
  380. sws_freeContext(swsCtx);
  381. // 复制时间戳等信息
  382. av_frame_copy_props(convertedFrame.get(), frame.get());
  383. return convertedFrame;
  384. }
  385. AVFramePtr VideoDecoder::transferFromHardware(AVFramePtr hwFrame) {
  386. if (!hwFrame || !isHardwareDecoder_) {
  387. return std::move(hwFrame);
  388. }
  389. // 创建软件帧
  390. AVFramePtr swFrame = makeAVFrame();
  391. if (!swFrame) {
  392. return nullptr;
  393. }
  394. // 从硬件传输到软件
  395. int ret = av_hwframe_transfer_data(swFrame.get(), hwFrame.get(), 0);
  396. if (ret < 0) {
  397. AV_LOGGER_ERRORF("从硬件传输数据失败: {}", ffmpeg_utils::errorToString(ret));
  398. return nullptr;
  399. }
  400. // 复制时间戳等信息
  401. av_frame_copy_props(swFrame.get(), hwFrame.get());
  402. return swFrame;
  403. }
  404. AVHWDeviceType VideoDecoder::getHardwareDeviceType() const {
  405. if (videoParams_.codecName.find("cuvid") != std::string::npos) {
  406. return AV_HWDEVICE_TYPE_CUDA;
  407. } else if (videoParams_.codecName.find("qsv") != std::string::npos) {
  408. return AV_HWDEVICE_TYPE_QSV;
  409. } else if (videoParams_.codecName.find("d3d11va") != std::string::npos) {
  410. return AV_HWDEVICE_TYPE_D3D11VA;
  411. } else if (videoParams_.codecName.find("videotoolbox") != std::string::npos) {
  412. return AV_HWDEVICE_TYPE_VIDEOTOOLBOX;
  413. }
  414. return AV_HWDEVICE_TYPE_NONE;
  415. }
  416. AVPixelFormat VideoDecoder::getHardwarePixelFormat() const {
  417. if (videoParams_.codecName.find("cuvid") != std::string::npos) {
  418. return AV_PIX_FMT_CUDA;
  419. } else if (videoParams_.codecName.find("qsv") != std::string::npos) {
  420. return AV_PIX_FMT_QSV;
  421. } else if (videoParams_.codecName.find("d3d11va") != std::string::npos) {
  422. return AV_PIX_FMT_D3D11;
  423. } else if (videoParams_.codecName.find("videotoolbox") != std::string::npos) {
  424. return AV_PIX_FMT_VIDEOTOOLBOX;
  425. }
  426. AV_LOGGER_ERRORF("未知的硬件解码器: {}", videoParams_.codecName);
  427. return AV_PIX_FMT_NONE;
  428. }
  429. void VideoDecoder::updateStats(bool success, double decodeTime, size_t dataSize) {
  430. std::lock_guard<std::mutex> lock(statsMutex_);
  431. if (success) {
  432. stats_.decodedFrames++;
  433. stats_.totalBytes += dataSize;
  434. // 更新平均解码时间
  435. if (stats_.decodedFrames == 1) {
  436. stats_.avgDecodeTime = decodeTime;
  437. } else {
  438. stats_.avgDecodeTime = (stats_.avgDecodeTime * (stats_.decodedFrames - 1) + decodeTime) / stats_.decodedFrames;
  439. }
  440. } else {
  441. stats_.errorCount++;
  442. }
  443. }
  444. VideoDecoder::DecoderStats VideoDecoder::getStats() const {
  445. std::lock_guard<std::mutex> lock(statsMutex_);
  446. return stats_;
  447. }
  448. void VideoDecoder::resetStats() {
  449. std::lock_guard<std::mutex> lock(statsMutex_);
  450. stats_ = DecoderStats{};
  451. }
  452. std::string VideoDecoder::getDecoderName() const {
  453. return videoParams_.codecName;
  454. }
  455. std::vector<std::string> VideoDecoder::getSupportedDecoders() {
  456. std::call_once(decodersInitFlag_, findUsableDecoders);
  457. return supportedDecoders_;
  458. }
  459. bool VideoDecoder::isHardwareDecoder(const std::string& codecName) {
  460. for (const char* hwDecoder : HARDWARE_DECODERS) {
  461. if (hwDecoder != nullptr && codecName == hwDecoder) {
  462. return true;
  463. }
  464. }
  465. return false;
  466. }
  467. std::string VideoDecoder::getRecommendedDecoder(const std::string& codecName) {
  468. auto decoders = getSupportedDecoders();
  469. if (!codecName.empty()) {
  470. // 查找指定编解码格式的最佳解码器
  471. std::string baseCodec = codecName;
  472. // 优先选择硬件解码器
  473. for (const char* hwDecoder : HARDWARE_DECODERS) {
  474. if (hwDecoder != nullptr) {
  475. std::string hwDecoderName = hwDecoder;
  476. if (hwDecoderName.find(baseCodec) != std::string::npos &&
  477. std::find(decoders.begin(), decoders.end(), hwDecoderName) != decoders.end()) {
  478. return hwDecoderName;
  479. }
  480. }
  481. }
  482. // 回退到软件解码器
  483. if (std::find(decoders.begin(), decoders.end(), baseCodec) != decoders.end()) {
  484. return baseCodec;
  485. }
  486. }
  487. // 返回第一个可用的硬件解码器
  488. for (const char* hwDecoder : HARDWARE_DECODERS) {
  489. if (hwDecoder != nullptr && std::find(decoders.begin(), decoders.end(), hwDecoder) != decoders.end()) {
  490. return hwDecoder;
  491. }
  492. }
  493. // 回退到软件解码器
  494. for (const char* swDecoder : SOFTWARE_DECODERS) {
  495. if (swDecoder != nullptr && std::find(decoders.begin(), decoders.end(), swDecoder) != decoders.end()) {
  496. return swDecoder;
  497. }
  498. }
  499. return decoders.empty() ? "" : decoders[0];
  500. }
  501. void VideoDecoder::findUsableDecoders() {
  502. AV_LOGGER_INFO("查找可用的视频解码器...");
  503. // 测试硬件解码器
  504. for (const char* decoder : HARDWARE_DECODERS) {
  505. if (decoder != nullptr && CodecFactory::isCodecSupported(decoder, CodecType::DECODER, MediaType::VIDEO)) {
  506. supportedDecoders_.emplace_back(decoder);
  507. AV_LOGGER_INFOF("找到硬件解码器: {}", decoder);
  508. }
  509. }
  510. // 测试软件解码器
  511. for (const char* decoder : SOFTWARE_DECODERS) {
  512. if (decoder != nullptr && CodecFactory::isCodecSupported(decoder, CodecType::DECODER, MediaType::VIDEO)) {
  513. supportedDecoders_.emplace_back(decoder);
  514. AV_LOGGER_INFOF("找到软件解码器: {}", decoder);
  515. }
  516. }
  517. AV_LOGGER_INFOF("总共找到 {} 个可用的视频解码器", supportedDecoders_.size());
  518. }
  519. // VideoDecoderFactory 实现
  520. std::unique_ptr<VideoDecoder> VideoDecoder::VideoDecoderFactory::create(const std::string& codecName) {
  521. auto decoder = std::make_unique<VideoDecoder>();
  522. if (!codecName.empty()) {
  523. if (!CodecFactory::isCodecSupported(codecName, CodecType::DECODER, MediaType::VIDEO)) {
  524. AV_LOGGER_ERRORF("不支持的解码器: {}", codecName);
  525. return nullptr;
  526. }
  527. }
  528. return decoder;
  529. }
  530. std::unique_ptr<VideoDecoder> VideoDecoder::VideoDecoderFactory::createBest(bool preferHardware) {
  531. std::string codecName;
  532. if (preferHardware) {
  533. codecName = VideoDecoder::getRecommendedDecoder();
  534. } else {
  535. // 优先选择软件解码器
  536. auto decoders = VideoDecoder::getSupportedDecoders();
  537. for (const char* swDecoder : VideoDecoder::SOFTWARE_DECODERS) {
  538. if (swDecoder != nullptr && std::find(decoders.begin(), decoders.end(), swDecoder) != decoders.end()) {
  539. codecName = swDecoder;
  540. break;
  541. }
  542. }
  543. }
  544. if (codecName.empty()) {
  545. AV_LOGGER_ERROR("未找到可用的视频解码器");
  546. return nullptr;
  547. }
  548. return create(codecName);
  549. }
  550. } // namespace codec
  551. } // namespace av