codec_video_decoder.cpp 20 KB

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