codec.cpp 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304
  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 <fstream>
  6. #include <vector>
  7. #include "common/assert.h"
  8. #include "common/settings.h"
  9. #include "video_core/command_classes/codecs/codec.h"
  10. #include "video_core/command_classes/codecs/h264.h"
  11. #include "video_core/command_classes/codecs/vp8.h"
  12. #include "video_core/command_classes/codecs/vp9.h"
  13. #include "video_core/gpu.h"
  14. #include "video_core/memory_manager.h"
  15. extern "C" {
  16. #include <libavutil/opt.h>
  17. #ifdef LIBVA_FOUND
  18. // for querying VAAPI driver information
  19. #include <libavutil/hwcontext_vaapi.h>
  20. #endif
  21. }
  22. namespace Tegra {
  23. namespace {
  24. constexpr AVPixelFormat PREFERRED_GPU_FMT = AV_PIX_FMT_NV12;
  25. constexpr AVPixelFormat PREFERRED_CPU_FMT = AV_PIX_FMT_YUV420P;
  26. constexpr std::array PREFERRED_GPU_DECODERS = {
  27. AV_HWDEVICE_TYPE_CUDA,
  28. #ifdef _WIN32
  29. AV_HWDEVICE_TYPE_D3D11VA,
  30. AV_HWDEVICE_TYPE_DXVA2,
  31. #elif defined(__unix__)
  32. AV_HWDEVICE_TYPE_VAAPI,
  33. AV_HWDEVICE_TYPE_VDPAU,
  34. #endif
  35. // last resort for Linux Flatpak (w/ NVIDIA)
  36. AV_HWDEVICE_TYPE_VULKAN,
  37. };
  38. void AVPacketDeleter(AVPacket* ptr) {
  39. av_packet_free(&ptr);
  40. }
  41. using AVPacketPtr = std::unique_ptr<AVPacket, decltype(&AVPacketDeleter)>;
  42. AVPixelFormat GetGpuFormat(AVCodecContext* av_codec_ctx, const AVPixelFormat* pix_fmts) {
  43. for (const AVPixelFormat* p = pix_fmts; *p != AV_PIX_FMT_NONE; ++p) {
  44. if (*p == av_codec_ctx->pix_fmt) {
  45. return av_codec_ctx->pix_fmt;
  46. }
  47. }
  48. LOG_INFO(Service_NVDRV, "Could not find compatible GPU AV format, falling back to CPU");
  49. av_buffer_unref(&av_codec_ctx->hw_device_ctx);
  50. av_codec_ctx->pix_fmt = PREFERRED_CPU_FMT;
  51. return PREFERRED_CPU_FMT;
  52. }
  53. } // namespace
  54. void AVFrameDeleter(AVFrame* ptr) {
  55. av_frame_free(&ptr);
  56. }
  57. Codec::Codec(GPU& gpu_, const NvdecCommon::NvdecRegisters& regs)
  58. : gpu(gpu_), state{regs}, h264_decoder(std::make_unique<Decoder::H264>(gpu)),
  59. vp8_decoder(std::make_unique<Decoder::VP8>(gpu)),
  60. vp9_decoder(std::make_unique<Decoder::VP9>(gpu)) {}
  61. Codec::~Codec() {
  62. if (!initialized) {
  63. return;
  64. }
  65. // Free libav memory
  66. avcodec_free_context(&av_codec_ctx);
  67. av_buffer_unref(&av_gpu_decoder);
  68. }
  69. // List all the currently available hwcontext in ffmpeg
  70. static std::vector<AVHWDeviceType> ListSupportedContexts() {
  71. std::vector<AVHWDeviceType> contexts{};
  72. AVHWDeviceType current_device_type = AV_HWDEVICE_TYPE_NONE;
  73. do {
  74. current_device_type = av_hwdevice_iterate_types(current_device_type);
  75. contexts.push_back(current_device_type);
  76. } while (current_device_type != AV_HWDEVICE_TYPE_NONE);
  77. return contexts;
  78. }
  79. bool Codec::CreateGpuAvDevice() {
  80. static constexpr auto HW_CONFIG_METHOD = AV_CODEC_HW_CONFIG_METHOD_HW_DEVICE_CTX;
  81. static const auto supported_contexts = ListSupportedContexts();
  82. for (const auto& type : PREFERRED_GPU_DECODERS) {
  83. if (std::none_of(supported_contexts.begin(), supported_contexts.end(),
  84. [&type](const auto& context) { return context == type; })) {
  85. LOG_DEBUG(Service_NVDRV, "{} explicitly unsupported", av_hwdevice_get_type_name(type));
  86. continue;
  87. }
  88. const int hwdevice_res = av_hwdevice_ctx_create(&av_gpu_decoder, type, nullptr, nullptr, 0);
  89. if (hwdevice_res < 0) {
  90. LOG_DEBUG(Service_NVDRV, "{} av_hwdevice_ctx_create failed {}",
  91. av_hwdevice_get_type_name(type), hwdevice_res);
  92. continue;
  93. }
  94. #ifdef LIBVA_FOUND
  95. if (type == AV_HWDEVICE_TYPE_VAAPI) {
  96. // we need to determine if this is an impersonated VAAPI driver
  97. AVHWDeviceContext* hwctx =
  98. static_cast<AVHWDeviceContext*>(static_cast<void*>(av_gpu_decoder->data));
  99. AVVAAPIDeviceContext* vactx = static_cast<AVVAAPIDeviceContext*>(hwctx->hwctx);
  100. const char* vendor_name = vaQueryVendorString(vactx->display);
  101. if (strstr(vendor_name, "VDPAU backend")) {
  102. // VDPAU impersonated VAAPI impl's are super buggy, we need to skip them
  103. LOG_DEBUG(Service_NVDRV, "Skipping vdapu impersonated VAAPI driver");
  104. continue;
  105. } else {
  106. // according to some user testing, certain vaapi driver (Intel?) could be buggy
  107. // so let's log the driver name which may help the developers/supporters
  108. LOG_DEBUG(Service_NVDRV, "Using VAAPI driver: {}", vendor_name);
  109. }
  110. }
  111. #endif
  112. for (int i = 0;; i++) {
  113. const AVCodecHWConfig* config = avcodec_get_hw_config(av_codec, i);
  114. if (!config) {
  115. LOG_DEBUG(Service_NVDRV, "{} decoder does not support device type {}.",
  116. av_codec->name, av_hwdevice_get_type_name(type));
  117. break;
  118. }
  119. if (config->methods & HW_CONFIG_METHOD && config->device_type == type) {
  120. av_codec_ctx->pix_fmt = config->pix_fmt;
  121. if (config->methods & AV_CODEC_HW_CONFIG_METHOD_HW_FRAMES_CTX) {
  122. // skip zero-copy decoders, we don't currently support them
  123. LOG_DEBUG(Service_NVDRV, "Skipping decoder {} with unsupported capability {}.",
  124. av_hwdevice_get_type_name(type), config->methods);
  125. continue;
  126. }
  127. LOG_INFO(Service_NVDRV, "Using {} GPU decoder", av_hwdevice_get_type_name(type));
  128. return true;
  129. }
  130. }
  131. }
  132. return false;
  133. }
  134. void Codec::InitializeAvCodecContext() {
  135. av_codec_ctx = avcodec_alloc_context3(av_codec);
  136. av_opt_set(av_codec_ctx->priv_data, "tune", "zerolatency", 0);
  137. }
  138. void Codec::InitializeGpuDecoder() {
  139. if (!CreateGpuAvDevice()) {
  140. av_buffer_unref(&av_gpu_decoder);
  141. return;
  142. }
  143. auto* hw_device_ctx = av_buffer_ref(av_gpu_decoder);
  144. ASSERT_MSG(hw_device_ctx, "av_buffer_ref failed");
  145. av_codec_ctx->hw_device_ctx = hw_device_ctx;
  146. av_codec_ctx->get_format = GetGpuFormat;
  147. }
  148. void Codec::Initialize() {
  149. const AVCodecID codec = [&] {
  150. switch (current_codec) {
  151. case NvdecCommon::VideoCodec::H264:
  152. return AV_CODEC_ID_H264;
  153. case NvdecCommon::VideoCodec::VP8:
  154. return AV_CODEC_ID_VP8;
  155. case NvdecCommon::VideoCodec::VP9:
  156. return AV_CODEC_ID_VP9;
  157. default:
  158. UNIMPLEMENTED_MSG("Unknown codec {}", current_codec);
  159. return AV_CODEC_ID_NONE;
  160. }
  161. }();
  162. av_codec = avcodec_find_decoder(codec);
  163. InitializeAvCodecContext();
  164. if (Settings::values.nvdec_emulation.GetValue() == Settings::NvdecEmulation::GPU) {
  165. InitializeGpuDecoder();
  166. }
  167. if (const int res = avcodec_open2(av_codec_ctx, av_codec, nullptr); res < 0) {
  168. LOG_ERROR(Service_NVDRV, "avcodec_open2() Failed with result {}", res);
  169. avcodec_free_context(&av_codec_ctx);
  170. av_buffer_unref(&av_gpu_decoder);
  171. return;
  172. }
  173. if (!av_codec_ctx->hw_device_ctx) {
  174. LOG_INFO(Service_NVDRV, "Using FFmpeg software decoding");
  175. }
  176. initialized = true;
  177. }
  178. void Codec::SetTargetCodec(NvdecCommon::VideoCodec codec) {
  179. if (current_codec != codec) {
  180. current_codec = codec;
  181. LOG_INFO(Service_NVDRV, "NVDEC video codec initialized to {}", GetCurrentCodecName());
  182. }
  183. }
  184. void Codec::Decode() {
  185. const bool is_first_frame = !initialized;
  186. if (is_first_frame) {
  187. Initialize();
  188. }
  189. if (!initialized) {
  190. return;
  191. }
  192. bool vp9_hidden_frame = false;
  193. const auto& frame_data = [&]() {
  194. switch (current_codec) {
  195. case Tegra::NvdecCommon::VideoCodec::H264:
  196. return h264_decoder->ComposeFrame(state, is_first_frame);
  197. case Tegra::NvdecCommon::VideoCodec::VP8:
  198. return vp8_decoder->ComposeFrame(state);
  199. case Tegra::NvdecCommon::VideoCodec::VP9:
  200. vp9_decoder->ComposeFrame(state);
  201. vp9_hidden_frame = vp9_decoder->WasFrameHidden();
  202. return vp9_decoder->GetFrameBytes();
  203. default:
  204. UNREACHABLE();
  205. return std::vector<u8>{};
  206. }
  207. }();
  208. AVPacketPtr packet{av_packet_alloc(), AVPacketDeleter};
  209. if (!packet) {
  210. LOG_ERROR(Service_NVDRV, "av_packet_alloc failed");
  211. return;
  212. }
  213. packet->data = const_cast<u8*>(frame_data.data());
  214. packet->size = static_cast<s32>(frame_data.size());
  215. if (const int res = avcodec_send_packet(av_codec_ctx, packet.get()); res != 0) {
  216. LOG_DEBUG(Service_NVDRV, "avcodec_send_packet error {}", res);
  217. return;
  218. }
  219. // Only receive/store visible frames
  220. if (vp9_hidden_frame) {
  221. return;
  222. }
  223. AVFramePtr initial_frame{av_frame_alloc(), AVFrameDeleter};
  224. AVFramePtr final_frame{nullptr, AVFrameDeleter};
  225. ASSERT_MSG(initial_frame, "av_frame_alloc initial_frame failed");
  226. if (const int ret = avcodec_receive_frame(av_codec_ctx, initial_frame.get()); ret) {
  227. LOG_DEBUG(Service_NVDRV, "avcodec_receive_frame error {}", ret);
  228. return;
  229. }
  230. if (initial_frame->width == 0 || initial_frame->height == 0) {
  231. LOG_WARNING(Service_NVDRV, "Zero width or height in frame");
  232. return;
  233. }
  234. if (av_codec_ctx->hw_device_ctx) {
  235. final_frame = AVFramePtr{av_frame_alloc(), AVFrameDeleter};
  236. ASSERT_MSG(final_frame, "av_frame_alloc final_frame failed");
  237. // Can't use AV_PIX_FMT_YUV420P and share code with software decoding in vic.cpp
  238. // because Intel drivers crash unless using AV_PIX_FMT_NV12
  239. final_frame->format = PREFERRED_GPU_FMT;
  240. const int ret = av_hwframe_transfer_data(final_frame.get(), initial_frame.get(), 0);
  241. ASSERT_MSG(!ret, "av_hwframe_transfer_data error {}", ret);
  242. } else {
  243. final_frame = std::move(initial_frame);
  244. }
  245. if (final_frame->format != PREFERRED_CPU_FMT && final_frame->format != PREFERRED_GPU_FMT) {
  246. UNIMPLEMENTED_MSG("Unexpected video format: {}", final_frame->format);
  247. return;
  248. }
  249. av_frames.push(std::move(final_frame));
  250. if (av_frames.size() > 10) {
  251. LOG_TRACE(Service_NVDRV, "av_frames.push overflow dropped frame");
  252. av_frames.pop();
  253. }
  254. }
  255. AVFramePtr Codec::GetCurrentFrame() {
  256. // Sometimes VIC will request more frames than have been decoded.
  257. // in this case, return a nullptr and don't overwrite previous frame data
  258. if (av_frames.empty()) {
  259. return AVFramePtr{nullptr, AVFrameDeleter};
  260. }
  261. AVFramePtr frame = std::move(av_frames.front());
  262. av_frames.pop();
  263. return frame;
  264. }
  265. NvdecCommon::VideoCodec Codec::GetCurrentCodec() const {
  266. return current_codec;
  267. }
  268. std::string_view Codec::GetCurrentCodecName() const {
  269. switch (current_codec) {
  270. case NvdecCommon::VideoCodec::None:
  271. return "None";
  272. case NvdecCommon::VideoCodec::H264:
  273. return "H264";
  274. case NvdecCommon::VideoCodec::VP8:
  275. return "VP8";
  276. case NvdecCommon::VideoCodec::H265:
  277. return "H265";
  278. case NvdecCommon::VideoCodec::VP9:
  279. return "VP9";
  280. default:
  281. return "Unknown";
  282. }
  283. }
  284. } // namespace Tegra