codec_video_decoder.cpp 22 KB

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