codec.cpp 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316
  1. // Copyright 2020 yuzu Emulator Project
  2. // Licensed under GPLv2 or any later version
  3. // Refer to the license.txt file included.
  4. #include <algorithm>
  5. #include <cstdio>
  6. #include <fstream>
  7. #include <vector>
  8. #include "common/assert.h"
  9. #include "common/settings.h"
  10. #include "video_core/command_classes/codecs/codec.h"
  11. #include "video_core/command_classes/codecs/h264.h"
  12. #include "video_core/command_classes/codecs/vp8.h"
  13. #include "video_core/command_classes/codecs/vp9.h"
  14. #include "video_core/gpu.h"
  15. #include "video_core/memory_manager.h"
  16. extern "C" {
  17. #include <libavutil/opt.h>
  18. }
  19. namespace Tegra {
  20. namespace {
  21. constexpr AVPixelFormat PREFERRED_GPU_FMT = AV_PIX_FMT_NV12;
  22. constexpr AVPixelFormat PREFERRED_CPU_FMT = AV_PIX_FMT_YUV420P;
  23. void AVPacketDeleter(AVPacket* ptr) {
  24. av_packet_free(&ptr);
  25. }
  26. using AVPacketPtr = std::unique_ptr<AVPacket, decltype(&AVPacketDeleter)>;
  27. AVPixelFormat GetGpuFormat(AVCodecContext* av_codec_ctx, const AVPixelFormat* pix_fmts) {
  28. for (const AVPixelFormat* p = pix_fmts; *p != AV_PIX_FMT_NONE; ++p) {
  29. if (*p == av_codec_ctx->pix_fmt) {
  30. return av_codec_ctx->pix_fmt;
  31. }
  32. }
  33. LOG_INFO(Service_NVDRV, "Could not find compatible GPU AV format, falling back to CPU");
  34. av_buffer_unref(&av_codec_ctx->hw_device_ctx);
  35. av_codec_ctx->pix_fmt = PREFERRED_CPU_FMT;
  36. return PREFERRED_CPU_FMT;
  37. }
  38. } // namespace
  39. void AVFrameDeleter(AVFrame* ptr) {
  40. av_frame_free(&ptr);
  41. }
  42. Codec::Codec(GPU& gpu_, const NvdecCommon::NvdecRegisters& regs)
  43. : gpu(gpu_), state{regs}, h264_decoder(std::make_unique<Decoder::H264>(gpu)),
  44. vp8_decoder(std::make_unique<Decoder::VP8>(gpu)),
  45. vp9_decoder(std::make_unique<Decoder::VP9>(gpu)) {}
  46. Codec::~Codec() {
  47. if (!initialized) {
  48. return;
  49. }
  50. // Free libav memory
  51. avcodec_free_context(&av_codec_ctx);
  52. av_buffer_unref(&av_gpu_decoder);
  53. }
  54. #ifdef LIBVA_FOUND
  55. // List all the currently loaded Linux modules
  56. static std::vector<std::string> ListLinuxKernelModules() {
  57. using FILEPtr = std::unique_ptr<FILE, decltype(&std::fclose)>;
  58. auto module_listing = FILEPtr{fopen("/proc/modules", "rt"), std::fclose};
  59. std::vector<std::string> modules{};
  60. if (!module_listing) {
  61. LOG_WARNING(Service_NVDRV, "Could not open /proc/modules to collect available modules");
  62. return modules;
  63. }
  64. char* buffer = nullptr;
  65. size_t buf_len = 0;
  66. while (getline(&buffer, &buf_len, module_listing.get()) != -1) {
  67. // format for the module listing file (sysfs)
  68. // <name> <module_size> <depended_by_count> <depended_by_names> <status> <load_address>
  69. auto line = std::string(buffer);
  70. // we are only interested in module names
  71. auto name_pos = line.find_first_of(" ");
  72. if (name_pos == std::string::npos) {
  73. continue;
  74. }
  75. modules.push_back(line.erase(name_pos));
  76. }
  77. free(buffer);
  78. return modules;
  79. }
  80. #endif
  81. bool Codec::CreateGpuAvDevice() {
  82. #if defined(LIBVA_FOUND)
  83. static constexpr std::array<const char*, 3> VAAPI_DRIVERS = {
  84. "i915",
  85. "iHD",
  86. "amdgpu",
  87. };
  88. AVDictionary* hwdevice_options = nullptr;
  89. const auto loaded_modules = ListLinuxKernelModules();
  90. av_dict_set(&hwdevice_options, "connection_type", "drm", 0);
  91. for (const auto& driver : VAAPI_DRIVERS) {
  92. // first check if the target driver is loaded in the kernel
  93. bool found = std::any_of(loaded_modules.begin(), loaded_modules.end(),
  94. [&driver](const auto& module) { return module == driver; });
  95. if (!found) {
  96. LOG_DEBUG(Service_NVDRV, "Kernel driver {} is not loaded, trying the next one", driver);
  97. continue;
  98. }
  99. av_dict_set(&hwdevice_options, "kernel_driver", driver, 0);
  100. const int hwdevice_error = av_hwdevice_ctx_create(&av_gpu_decoder, AV_HWDEVICE_TYPE_VAAPI,
  101. nullptr, hwdevice_options, 0);
  102. if (hwdevice_error >= 0) {
  103. LOG_INFO(Service_NVDRV, "Using VA-API with {}", driver);
  104. av_dict_free(&hwdevice_options);
  105. av_codec_ctx->pix_fmt = AV_PIX_FMT_VAAPI;
  106. return true;
  107. }
  108. LOG_DEBUG(Service_NVDRV, "VA-API av_hwdevice_ctx_create failed {}", hwdevice_error);
  109. }
  110. LOG_DEBUG(Service_NVDRV, "VA-API av_hwdevice_ctx_create failed for all drivers");
  111. av_dict_free(&hwdevice_options);
  112. #endif
  113. static constexpr auto HW_CONFIG_METHOD = AV_CODEC_HW_CONFIG_METHOD_HW_DEVICE_CTX;
  114. static constexpr std::array GPU_DECODER_TYPES{
  115. #ifdef linux
  116. AV_HWDEVICE_TYPE_VDPAU,
  117. #endif
  118. AV_HWDEVICE_TYPE_CUDA,
  119. #ifdef _WIN32
  120. AV_HWDEVICE_TYPE_D3D11VA,
  121. #endif
  122. };
  123. for (const auto& type : GPU_DECODER_TYPES) {
  124. const int hwdevice_res = av_hwdevice_ctx_create(&av_gpu_decoder, type, nullptr, nullptr, 0);
  125. if (hwdevice_res < 0) {
  126. LOG_DEBUG(Service_NVDRV, "{} av_hwdevice_ctx_create failed {}",
  127. av_hwdevice_get_type_name(type), hwdevice_res);
  128. continue;
  129. }
  130. for (int i = 0;; i++) {
  131. const AVCodecHWConfig* config = avcodec_get_hw_config(av_codec, i);
  132. if (!config) {
  133. LOG_DEBUG(Service_NVDRV, "{} decoder does not support device type {}.",
  134. av_codec->name, av_hwdevice_get_type_name(type));
  135. break;
  136. }
  137. if (config->methods & HW_CONFIG_METHOD && config->device_type == type) {
  138. av_codec_ctx->pix_fmt = config->pix_fmt;
  139. LOG_INFO(Service_NVDRV, "Using {} GPU decoder", av_hwdevice_get_type_name(type));
  140. return true;
  141. }
  142. }
  143. }
  144. return false;
  145. }
  146. void Codec::InitializeAvCodecContext() {
  147. av_codec_ctx = avcodec_alloc_context3(av_codec);
  148. av_opt_set(av_codec_ctx->priv_data, "tune", "zerolatency", 0);
  149. }
  150. void Codec::InitializeGpuDecoder() {
  151. if (!CreateGpuAvDevice()) {
  152. av_buffer_unref(&av_gpu_decoder);
  153. return;
  154. }
  155. auto* hw_device_ctx = av_buffer_ref(av_gpu_decoder);
  156. ASSERT_MSG(hw_device_ctx, "av_buffer_ref failed");
  157. av_codec_ctx->hw_device_ctx = hw_device_ctx;
  158. av_codec_ctx->get_format = GetGpuFormat;
  159. }
  160. void Codec::Initialize() {
  161. const AVCodecID codec = [&] {
  162. switch (current_codec) {
  163. case NvdecCommon::VideoCodec::H264:
  164. return AV_CODEC_ID_H264;
  165. case NvdecCommon::VideoCodec::VP8:
  166. return AV_CODEC_ID_VP8;
  167. case NvdecCommon::VideoCodec::VP9:
  168. return AV_CODEC_ID_VP9;
  169. default:
  170. UNIMPLEMENTED_MSG("Unknown codec {}", current_codec);
  171. return AV_CODEC_ID_NONE;
  172. }
  173. }();
  174. av_codec = avcodec_find_decoder(codec);
  175. InitializeAvCodecContext();
  176. if (Settings::values.nvdec_emulation.GetValue() == Settings::NvdecEmulation::GPU) {
  177. InitializeGpuDecoder();
  178. }
  179. if (const int res = avcodec_open2(av_codec_ctx, av_codec, nullptr); res < 0) {
  180. LOG_ERROR(Service_NVDRV, "avcodec_open2() Failed with result {}", res);
  181. avcodec_free_context(&av_codec_ctx);
  182. av_buffer_unref(&av_gpu_decoder);
  183. return;
  184. }
  185. if (!av_codec_ctx->hw_device_ctx) {
  186. LOG_INFO(Service_NVDRV, "Using FFmpeg software decoding");
  187. }
  188. initialized = true;
  189. }
  190. void Codec::SetTargetCodec(NvdecCommon::VideoCodec codec) {
  191. if (current_codec != codec) {
  192. current_codec = codec;
  193. LOG_INFO(Service_NVDRV, "NVDEC video codec initialized to {}", GetCurrentCodecName());
  194. }
  195. }
  196. void Codec::Decode() {
  197. const bool is_first_frame = !initialized;
  198. if (is_first_frame) {
  199. Initialize();
  200. }
  201. if (!initialized) {
  202. return;
  203. }
  204. bool vp9_hidden_frame = false;
  205. const auto& frame_data = [&]() {
  206. switch (current_codec) {
  207. case Tegra::NvdecCommon::VideoCodec::H264:
  208. return h264_decoder->ComposeFrame(state, is_first_frame);
  209. case Tegra::NvdecCommon::VideoCodec::VP8:
  210. return vp8_decoder->ComposeFrame(state);
  211. case Tegra::NvdecCommon::VideoCodec::VP9:
  212. vp9_decoder->ComposeFrame(state);
  213. vp9_hidden_frame = vp9_decoder->WasFrameHidden();
  214. return vp9_decoder->GetFrameBytes();
  215. default:
  216. UNREACHABLE();
  217. return std::vector<u8>{};
  218. }
  219. }();
  220. AVPacketPtr packet{av_packet_alloc(), AVPacketDeleter};
  221. if (!packet) {
  222. LOG_ERROR(Service_NVDRV, "av_packet_alloc failed");
  223. return;
  224. }
  225. packet->data = const_cast<u8*>(frame_data.data());
  226. packet->size = static_cast<s32>(frame_data.size());
  227. if (const int res = avcodec_send_packet(av_codec_ctx, packet.get()); res != 0) {
  228. LOG_DEBUG(Service_NVDRV, "avcodec_send_packet error {}", res);
  229. return;
  230. }
  231. // Only receive/store visible frames
  232. if (vp9_hidden_frame) {
  233. return;
  234. }
  235. AVFramePtr initial_frame{av_frame_alloc(), AVFrameDeleter};
  236. AVFramePtr final_frame{nullptr, AVFrameDeleter};
  237. ASSERT_MSG(initial_frame, "av_frame_alloc initial_frame failed");
  238. if (const int ret = avcodec_receive_frame(av_codec_ctx, initial_frame.get()); ret) {
  239. LOG_DEBUG(Service_NVDRV, "avcodec_receive_frame error {}", ret);
  240. return;
  241. }
  242. if (initial_frame->width == 0 || initial_frame->height == 0) {
  243. LOG_WARNING(Service_NVDRV, "Zero width or height in frame");
  244. return;
  245. }
  246. if (av_codec_ctx->hw_device_ctx) {
  247. final_frame = AVFramePtr{av_frame_alloc(), AVFrameDeleter};
  248. ASSERT_MSG(final_frame, "av_frame_alloc final_frame failed");
  249. // Can't use AV_PIX_FMT_YUV420P and share code with software decoding in vic.cpp
  250. // because Intel drivers crash unless using AV_PIX_FMT_NV12
  251. final_frame->format = PREFERRED_GPU_FMT;
  252. const int ret = av_hwframe_transfer_data(final_frame.get(), initial_frame.get(), 0);
  253. ASSERT_MSG(!ret, "av_hwframe_transfer_data error {}", ret);
  254. } else {
  255. final_frame = std::move(initial_frame);
  256. }
  257. if (final_frame->format != PREFERRED_CPU_FMT && final_frame->format != PREFERRED_GPU_FMT) {
  258. UNIMPLEMENTED_MSG("Unexpected video format: {}", final_frame->format);
  259. return;
  260. }
  261. av_frames.push(std::move(final_frame));
  262. if (av_frames.size() > 10) {
  263. LOG_TRACE(Service_NVDRV, "av_frames.push overflow dropped frame");
  264. av_frames.pop();
  265. }
  266. }
  267. AVFramePtr Codec::GetCurrentFrame() {
  268. // Sometimes VIC will request more frames than have been decoded.
  269. // in this case, return a nullptr and don't overwrite previous frame data
  270. if (av_frames.empty()) {
  271. return AVFramePtr{nullptr, AVFrameDeleter};
  272. }
  273. AVFramePtr frame = std::move(av_frames.front());
  274. av_frames.pop();
  275. return frame;
  276. }
  277. NvdecCommon::VideoCodec Codec::GetCurrentCodec() const {
  278. return current_codec;
  279. }
  280. std::string_view Codec::GetCurrentCodecName() const {
  281. switch (current_codec) {
  282. case NvdecCommon::VideoCodec::None:
  283. return "None";
  284. case NvdecCommon::VideoCodec::H264:
  285. return "H264";
  286. case NvdecCommon::VideoCodec::VP8:
  287. return "VP8";
  288. case NvdecCommon::VideoCodec::H265:
  289. return "H265";
  290. case NvdecCommon::VideoCodec::VP9:
  291. return "VP9";
  292. default:
  293. return "Unknown";
  294. }
  295. }
  296. } // namespace Tegra