codec_video_decoder.cpp 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639
  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::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::SUCCESS) {
  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::SUCCESS) {
  54. return result;
  55. }
  56. setState(CodecState::OPENED);
  57. AV_LOGGER_INFOF("视频解码器已打开: {} ({}x{})",
  58. videoParams_.codecName,
  59. codecCtx_->width, codecCtx_->height);
  60. return ErrorCode::SUCCESS;
  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::SUCCESS;
  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::SUCCESS, 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_PARAMS;
  138. }
  139. // 创建解码上下文
  140. codecCtx_ = makeAVCodecContext(codec_);
  141. if (!codecCtx_) {
  142. AV_LOGGER_ERROR("分配解码上下文失败");
  143. return ErrorCode::MEMORY_ALLOC_FAILED;
  144. }
  145. // 设置硬件加速
  146. if (videoParams_.hardwareAccel && isHardwareDecoder(videoParams_.codecName)) {
  147. ErrorCode result = setupHardwareAcceleration();
  148. if (result != ErrorCode::SUCCESS) {
  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::SUCCESS) {
  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::SUCCESS;
  192. }
  193. ErrorCode VideoDecoder::setupDecoderParams() {
  194. // 设置视频尺寸
  195. if (videoParams_.width > 0 && videoParams_.height > 0) {
  196. codecCtx_->width = videoParams_.width;
  197. codecCtx_->height = videoParams_.height;
  198. }
  199. // 设置线程数
  200. if (videoParams_.threadCount > 0) {
  201. codecCtx_->thread_count = videoParams_.threadCount;
  202. } else {
  203. codecCtx_->thread_count = std::thread::hardware_concurrency();
  204. }
  205. // 设置像素格式(如果指定)
  206. if (videoParams_.pixelFormat != AV_PIX_FMT_NONE) {
  207. codecCtx_->pix_fmt = videoParams_.pixelFormat;
  208. }
  209. // 低延迟设置
  210. if (videoParams_.lowLatency) {
  211. codecCtx_->flags |= AV_CODEC_FLAG_LOW_DELAY;
  212. codecCtx_->flags2 |= AV_CODEC_FLAG2_FAST;
  213. }
  214. // 针对不同解码器设置特定参数
  215. if (videoParams_.codecName.find("cuvid") != std::string::npos) {
  216. // NVIDIA CUVID 特定参数
  217. if (codecCtx_->priv_data) {
  218. av_opt_set_int(codecCtx_->priv_data, "surfaces", 8, 0);
  219. if (videoParams_.lowLatency) {
  220. av_opt_set_int(codecCtx_->priv_data, "delay", 0, 0);
  221. }
  222. }
  223. } else if (videoParams_.codecName.find("qsv") != std::string::npos) {
  224. // Intel QSV 特定参数
  225. if (videoParams_.lowLatency && codecCtx_->priv_data) {
  226. av_opt_set(codecCtx_->priv_data, "async_depth", "1", 0);
  227. }
  228. }
  229. return ErrorCode::SUCCESS;
  230. }
  231. ErrorCode VideoDecoder::setupHardwareAcceleration() {
  232. isHardwareDecoder_ = true;
  233. AVHWDeviceType hwType = getHardwareDeviceType();
  234. if (hwType == AV_HWDEVICE_TYPE_NONE) {
  235. AV_LOGGER_ERRORF("不支持的硬件解码器: {}", videoParams_.codecName);
  236. return ErrorCode::NOT_SUPPORTED;
  237. }
  238. AV_LOGGER_INFOF("开始设置硬件加速: 解码器={}, 设备类型={}",
  239. videoParams_.codecName, static_cast<int>(hwType));
  240. // 创建硬件设备上下文
  241. AV_LOGGER_INFO("创建硬件设备上下文...");
  242. int ret = av_hwdevice_ctx_create(&hwDeviceCtx_, hwType, nullptr, nullptr, 0);
  243. if (ret < 0) {
  244. AV_LOGGER_ERRORF("创建硬件设备上下文失败: {} (解码器: {}, 错误码: {})",
  245. ffmpeg_utils::errorToString(ret), videoParams_.codecName, ret);
  246. // 特定错误处理
  247. if (ret == AVERROR(ENOENT)) {
  248. AV_LOGGER_ERROR("硬件设备不存在或驱动未安装");
  249. if (hwType == AV_HWDEVICE_TYPE_CUDA) {
  250. AV_LOGGER_ERROR("请检查NVIDIA驱动和CUDA是否正确安装");
  251. }
  252. } else if (ret == AVERROR(EBUSY)) {
  253. AV_LOGGER_ERROR("硬件设备正在被其他进程使用");
  254. } else if (ret == AVERROR(EINVAL)) {
  255. AV_LOGGER_ERROR("硬件设备参数无效");
  256. } else if (ret == AVERROR(ENOMEM)) {
  257. AV_LOGGER_ERROR("内存不足,无法创建硬件设备上下文");
  258. }
  259. return static_cast<ErrorCode>(ret);
  260. }
  261. AV_LOGGER_INFOF("硬件设备上下文创建成功: {}", videoParams_.codecName);
  262. // 设置硬件设备上下文到解码器
  263. codecCtx_->hw_device_ctx = av_buffer_ref(hwDeviceCtx_);
  264. return ErrorCode::SUCCESS;
  265. }
  266. ErrorCode VideoDecoder::decodeFrame(const AVPacketPtr& packet, std::vector<AVFramePtr>& frames) {
  267. // 发送包到解码器
  268. int ret = avcodec_send_packet(codecCtx_.get(), packet ? packet.get() : nullptr);
  269. if (ret < 0 && ret != AVERROR_EOF) {
  270. AV_LOGGER_ERRORF("发送包到解码器失败: {}", ffmpeg_utils::errorToString(ret));
  271. return static_cast<ErrorCode>(ret);
  272. }
  273. // 接收解码后的帧
  274. return receiveFrames(frames);
  275. }
  276. ErrorCode VideoDecoder::receiveFrames(std::vector<AVFramePtr>& frames) {
  277. while (true) {
  278. AVFramePtr frame = makeAVFrame();
  279. if (!frame) {
  280. return ErrorCode::MEMORY_ALLOC_FAILED;
  281. }
  282. int ret = avcodec_receive_frame(codecCtx_.get(), frame.get());
  283. if (ret == AVERROR(EAGAIN) || ret == AVERROR_EOF) {
  284. break; // 需要更多输入或已结束
  285. }
  286. if (ret < 0) {
  287. AV_LOGGER_ERRORF("接收解码帧失败: {}", ffmpeg_utils::errorToString(ret));
  288. return static_cast<ErrorCode>(ret);
  289. }
  290. // 处理硬件帧
  291. AVFramePtr processedFrame;
  292. if (isHardwareDecoder_) {
  293. processedFrame = transferFromHardware(std::move(frame));
  294. if (!processedFrame) {
  295. AV_LOGGER_ERROR("硬件帧传输失败");
  296. continue;
  297. }
  298. } else {
  299. processedFrame = std::move(frame);
  300. }
  301. // 格式转换(如果需要)
  302. auto convertedFrame = convertFrame(processedFrame);
  303. if (convertedFrame) {
  304. frames.push_back(std::move(convertedFrame));
  305. } else {
  306. frames.push_back(std::move(processedFrame));
  307. }
  308. }
  309. return ErrorCode::SUCCESS;
  310. }
  311. AVFramePtr VideoDecoder::convertFrame(const AVFramePtr& frame) {
  312. if (!frame) {
  313. return nullptr;
  314. }
  315. // 如果格式已经匹配,直接返回
  316. if (frame->format == videoParams_.pixelFormat) {
  317. return nullptr; // 不需要转换,返回nullptr表示使用原帧
  318. }
  319. // 创建转换后的帧
  320. AVFramePtr convertedFrame = makeAVFrame();
  321. if (!convertedFrame) {
  322. return nullptr;
  323. }
  324. convertedFrame->format = videoParams_.pixelFormat;
  325. convertedFrame->width = frame->width;
  326. convertedFrame->height = frame->height;
  327. if (av_frame_get_buffer(convertedFrame.get(), 32) < 0) {
  328. AV_LOGGER_ERROR("分配转换帧缓冲区失败");
  329. return nullptr;
  330. }
  331. // 使用 swscale 进行格式转换
  332. SwsContext* swsCtx = sws_getContext(
  333. frame->width, frame->height, static_cast<AVPixelFormat>(frame->format),
  334. convertedFrame->width, convertedFrame->height, videoParams_.pixelFormat,
  335. SWS_BILINEAR, nullptr, nullptr, nullptr
  336. );
  337. if (!swsCtx) {
  338. AV_LOGGER_ERROR("创建像素格式转换上下文失败");
  339. return nullptr;
  340. }
  341. sws_scale(swsCtx, frame->data, frame->linesize, 0, frame->height,
  342. convertedFrame->data, convertedFrame->linesize);
  343. sws_freeContext(swsCtx);
  344. // 复制时间戳等信息
  345. av_frame_copy_props(convertedFrame.get(), frame.get());
  346. return convertedFrame;
  347. }
  348. AVFramePtr VideoDecoder::transferFromHardware(AVFramePtr hwFrame) {
  349. if (!hwFrame || !isHardwareDecoder_) {
  350. return std::move(hwFrame);
  351. }
  352. // 创建软件帧
  353. AVFramePtr swFrame = makeAVFrame();
  354. if (!swFrame) {
  355. return nullptr;
  356. }
  357. // 从硬件传输到软件
  358. int ret = av_hwframe_transfer_data(swFrame.get(), hwFrame.get(), 0);
  359. if (ret < 0) {
  360. AV_LOGGER_ERRORF("从硬件传输数据失败: {}", ffmpeg_utils::errorToString(ret));
  361. return nullptr;
  362. }
  363. // 复制时间戳等信息
  364. av_frame_copy_props(swFrame.get(), hwFrame.get());
  365. return swFrame;
  366. }
  367. AVHWDeviceType VideoDecoder::getHardwareDeviceType() const {
  368. if (videoParams_.codecName.find("cuvid") != std::string::npos) {
  369. return AV_HWDEVICE_TYPE_CUDA;
  370. } else if (videoParams_.codecName.find("qsv") != std::string::npos) {
  371. return AV_HWDEVICE_TYPE_QSV;
  372. } else if (videoParams_.codecName.find("d3d11va") != std::string::npos) {
  373. return AV_HWDEVICE_TYPE_D3D11VA;
  374. } else if (videoParams_.codecName.find("videotoolbox") != std::string::npos) {
  375. return AV_HWDEVICE_TYPE_VIDEOTOOLBOX;
  376. }
  377. return AV_HWDEVICE_TYPE_NONE;
  378. }
  379. AVPixelFormat VideoDecoder::getHardwarePixelFormat() const {
  380. if (videoParams_.codecName.find("cuvid") != std::string::npos) {
  381. return AV_PIX_FMT_CUDA;
  382. } else if (videoParams_.codecName.find("qsv") != std::string::npos) {
  383. return AV_PIX_FMT_QSV;
  384. } else if (videoParams_.codecName.find("d3d11va") != std::string::npos) {
  385. return AV_PIX_FMT_D3D11;
  386. } else if (videoParams_.codecName.find("videotoolbox") != std::string::npos) {
  387. return AV_PIX_FMT_VIDEOTOOLBOX;
  388. }
  389. AV_LOGGER_ERRORF("未知的硬件解码器: {}", videoParams_.codecName);
  390. return AV_PIX_FMT_NONE;
  391. }
  392. void VideoDecoder::updateStats(bool success, double decodeTime, size_t dataSize) {
  393. std::lock_guard<std::mutex> lock(statsMutex_);
  394. if (success) {
  395. stats_.decodedFrames++;
  396. stats_.totalBytes += dataSize;
  397. // 更新平均解码时间
  398. if (stats_.decodedFrames == 1) {
  399. stats_.avgDecodeTime = decodeTime;
  400. } else {
  401. stats_.avgDecodeTime = (stats_.avgDecodeTime * (stats_.decodedFrames - 1) + decodeTime) / stats_.decodedFrames;
  402. }
  403. } else {
  404. stats_.errorCount++;
  405. }
  406. }
  407. VideoDecoder::DecoderStats VideoDecoder::getStats() const {
  408. std::lock_guard<std::mutex> lock(statsMutex_);
  409. return stats_;
  410. }
  411. void VideoDecoder::resetStats() {
  412. std::lock_guard<std::mutex> lock(statsMutex_);
  413. stats_ = DecoderStats{};
  414. }
  415. std::string VideoDecoder::getDecoderName() const {
  416. return videoParams_.codecName;
  417. }
  418. std::vector<std::string> VideoDecoder::getSupportedDecoders() {
  419. std::call_once(decodersInitFlag_, findUsableDecoders);
  420. return supportedDecoders_;
  421. }
  422. bool VideoDecoder::isHardwareDecoder(const std::string& codecName) {
  423. for (const char* hwDecoder : HARDWARE_DECODERS) {
  424. if (hwDecoder != nullptr && codecName == hwDecoder) {
  425. return true;
  426. }
  427. }
  428. return false;
  429. }
  430. std::string VideoDecoder::getRecommendedDecoder(const std::string& codecName) {
  431. auto decoders = getSupportedDecoders();
  432. if (!codecName.empty()) {
  433. // 查找指定编解码格式的最佳解码器
  434. std::string baseCodec = codecName;
  435. // 优先选择硬件解码器
  436. for (const char* hwDecoder : HARDWARE_DECODERS) {
  437. if (hwDecoder != nullptr) {
  438. std::string hwDecoderName = hwDecoder;
  439. if (hwDecoderName.find(baseCodec) != std::string::npos &&
  440. std::find(decoders.begin(), decoders.end(), hwDecoderName) != decoders.end()) {
  441. return hwDecoderName;
  442. }
  443. }
  444. }
  445. // 回退到软件解码器
  446. if (std::find(decoders.begin(), decoders.end(), baseCodec) != decoders.end()) {
  447. return baseCodec;
  448. }
  449. }
  450. // 返回第一个可用的硬件解码器
  451. for (const char* hwDecoder : HARDWARE_DECODERS) {
  452. if (hwDecoder != nullptr && std::find(decoders.begin(), decoders.end(), hwDecoder) != decoders.end()) {
  453. return hwDecoder;
  454. }
  455. }
  456. // 回退到软件解码器
  457. for (const char* swDecoder : SOFTWARE_DECODERS) {
  458. if (swDecoder != nullptr && std::find(decoders.begin(), decoders.end(), swDecoder) != decoders.end()) {
  459. return swDecoder;
  460. }
  461. }
  462. return decoders.empty() ? "" : decoders[0];
  463. }
  464. void VideoDecoder::findUsableDecoders() {
  465. AV_LOGGER_INFO("查找可用的视频解码器...");
  466. // 测试硬件解码器
  467. for (const char* decoder : HARDWARE_DECODERS) {
  468. if (decoder != nullptr && CodecFactory::isCodecSupported(decoder, CodecType::DECODER, MediaType::VIDEO)) {
  469. supportedDecoders_.emplace_back(decoder);
  470. AV_LOGGER_INFOF("找到硬件解码器: {}", decoder);
  471. }
  472. }
  473. // 测试软件解码器
  474. for (const char* decoder : SOFTWARE_DECODERS) {
  475. if (decoder != nullptr && CodecFactory::isCodecSupported(decoder, CodecType::DECODER, MediaType::VIDEO)) {
  476. supportedDecoders_.emplace_back(decoder);
  477. AV_LOGGER_INFOF("找到软件解码器: {}", decoder);
  478. }
  479. }
  480. AV_LOGGER_INFOF("总共找到 {} 个可用的视频解码器", supportedDecoders_.size());
  481. }
  482. // VideoDecoderFactory 实现
  483. std::unique_ptr<VideoDecoder> VideoDecoder::VideoDecoderFactory::create(const std::string& codecName) {
  484. auto decoder = std::make_unique<VideoDecoder>();
  485. if (!codecName.empty()) {
  486. if (!CodecFactory::isCodecSupported(codecName, CodecType::DECODER, MediaType::VIDEO)) {
  487. AV_LOGGER_ERRORF("不支持的解码器: {}", codecName);
  488. return nullptr;
  489. }
  490. }
  491. return decoder;
  492. }
  493. std::unique_ptr<VideoDecoder> VideoDecoder::VideoDecoderFactory::createBest(bool preferHardware) {
  494. std::string codecName;
  495. if (preferHardware) {
  496. codecName = VideoDecoder::getRecommendedDecoder();
  497. } else {
  498. // 优先选择软件解码器
  499. auto decoders = VideoDecoder::getSupportedDecoders();
  500. for (const char* swDecoder : VideoDecoder::SOFTWARE_DECODERS) {
  501. if (swDecoder != nullptr && std::find(decoders.begin(), decoders.end(), swDecoder) != decoders.end()) {
  502. codecName = swDecoder;
  503. break;
  504. }
  505. }
  506. }
  507. if (codecName.empty()) {
  508. AV_LOGGER_ERROR("未找到可用的视频解码器");
  509. return nullptr;
  510. }
  511. return create(codecName);
  512. }
  513. } // namespace codec
  514. } // namespace av